#! /usr/bin/env ruby
#
# file : ~/bin/loop
#
# synopis: shell looping that's easier that the bloody shell syntax 
#
# usage:
#
#   cfp:~ > loop n=2 echo @n
#   0
#   1
#
#   cfp:~ > loop x=3 echo @x
#   0
#   1
#   2
#
#   cfp:~ > loop n=4 iso8601
#   2007-09-28T09:24:01.40-06:00
#   2007-09-28T09:24:01.47-06:00
#   2007-09-28T09:24:01.55-06:00
#   2007-09-28T09:24:01.62-06:00
#

$VERBOSE = nil

var = 'n'
n = ENV['n'] || ENV['N']

if n.nil? and ARGV.first =~ %r/^([^=]+)=([0-9]+)$/i
  ARGV.shift
  var = $1
  n = $2
end

n = n.to_i
n = nil unless n > 0

cmd = ARGV.join(' ')
cmd = STDIN.read if cmd == '-'

i = 0 and loop do
  c = cmd.gsub %r/@#{ var }/, i.to_s
  IO.popen '/bin/sh', 'w' do |fd|
    fd.puts "#{ var }=#{ n } #{ c }"
    fd.close_write
    fd.read rescue nil
  end
  abort "<#{ cmd }> failed with <#{ $?.inspect }>" unless $?.exitstatus.zero?
  i += 1
  break if n and i >= n
end