#
# import ruby

IGNORE = ['eval.c', 'version.c', 'inits.c']

def output_filename f
  "_.#{f}".tr('/', '_')
end

def diff rubydir, *files
  raise "specify ruby HEAD directory" unless rubydir
  
  if files.size == 0
    files = (Dir.glob('**/*.[chy]') + Dir.glob('**/*.rb') +
             Dir.glob('**/configure*') + Dir.glob('**/*.sub')).sort.uniq
  end
  
  files.each{|f|
    rubyfile = File.join(rubydir, f)
    if FileTest.exist?(rubyfile) && !IGNORE.include?(f)
      diff = `diff -b -U 8 "#{f}" "#{rubyfile}"`
      if diff.size > 0
        p f
        open(output_filename(f), 'w'){|f|
          f.write diff
        }
        puts diff
      end
    end
  }
end

def patch file
  raise "specify patched file: #{(file||'').dump}" if !file || !FileTest.exist?(file)
  raise "no patch file: #{output_filename(file)}" if !FileTest.exist?(output_filename(file))
  cmd = "patch -lp0 --no-backup-if-mismatch -i #{output_filename(file)}"
  puts cmd
  
  if system(cmd)
    `rm "#{output_filename(file)}"`
  end
end

def cleanup
  system('rm -f _.* *.rej *.orig')
end


case ARGV[0]
when 'diff'
  diff(*ARGV[1..-1])
when 'patch'
  raise if ARGV[1..-1].size == 0
  ARGV[1..-1].each{|file|
    patch file
  }
when 'cleanup'
  cleanup
else
  raise "command: diff/patch/cleanup"
end
