#!/usr/bin/ruby

unless ARGV.size == 2
    puts "Usage: #{File.basename($0)} <file> <command>"
    exit 1
end

file = ARGV.shift
command = ARGV.shift

unless test(?f, file)
    puts "Invalid file: #{file}"
    exit 1
end

mt = File.stat(file).mtime

pid = nil

puts "+++ Watching ..."
begin
    loop do
        Process.wait(-1, Process::WNOHANG) rescue nil
        mt_new = File.stat(file).mtime rescue next
        unless mt_new == mt
            puts "+++ File (#{file}) changed ... launching command."
            if pid
                Process.kill(9, pid) if (Process.kill(0, pid) rescue nil)
                pid = nil
            end
            pid = fork do
                Kernel.exec("sh", "-c", command)
            end
            puts "+++ Watching ..."
            mt = mt_new
        end
        sleep 0.5
    end
rescue Interrupt
end