#! /usr/bin/ruby
# grepgrep dir re1 re2
#   - find files matching re1 under dir and then grep re2 in those files
# 
# regular expressions are ruby ones
#
# ignore case
#   icase=1 grepgrep ~/rem foo bar
#   icase=2 grepgrep ~/rem foo bar
#   icase=both grepgrep ~/rem foo bar
#

require 'find'

def grepgrep(f, re1, re2)
  match1 = false
  matches2 = []
  n = 0
  File.open(f) { |fd|
    fd.each_line { |s|
      n += 1
      match1 = true if s =~ re1
      matches2 << [n,s] if s =~ re2
    }
  }
  return unless match1
  matches2.each { |a|
    (n,s) = a
    puts "#{f}:#{n}:#{s}"
  }
end

exit 1 if ARGV.length != 3
(dir, re1, re2) = ARGV
icase = ENV['icase']
re1 = Regexp.new(re1, icase == '1' || icase == 'both')
re2 = Regexp.new(re2, icase == '2' || icase == 'both')
Find.find(dir) { |f|
  next unless File.stat(f).file?
  grepgrep(f, re1, re2)
}
