#!/usr/bin/ruby
#
# jgrep.rb -- 日本語 (EUC, Shift-JIS, JIS) 対応 grep
#
# Usage: jgrep.rb pattern files
#
# 履歴: 2003/11/24 森川
#        - 神戸大学の児玉 宏児(Kouji KODAMA)さんのサイトの
#          Tips よりパクって来る
#
#       2003/11/24 森川
#        - 勉強がてら, 機能を付加して遊んでみる
#
# バグ: エラー出力も標準出力に吐いてしまう
#
#
require 'kconv'
require 'find'
require 'getopts'

# オプション解析
unless getopts("hHr", "help", "recursive")
  print "jgrep.rb: illegal option.\n"
  exit 1
end

num = ARGV.size         # 引数の数を取得
# 指定した引数が足りない場合プログラム終了.
if (num < 2) || ($OPT_h) || ($OPT_H) || ($OPT_help) then
  print <<-"EOF"
  jgrep.rb:
    USAGE:
      jgrep.rb [option] pattern files [file...]

    OPTION:
      -h, -H, --help :  この、ヘルプメッセージを出力
      -r, --recursive: 再帰的に検索

  created by morikawa @ 2003-11-24
  EOF
  exit
end

# 1つ目の要素をパターンとして取り出す
pat=/#{Kconv::toeuc(ARGV.shift)}/e

ARGV.each{|fname|
  # 再帰的検索
  if ($OPT_r || $OPT_recursive) then
    Find.find(*fname) do |path|
      if (! File.exist?(path)) then
        print path, " is not found.\n"
      elsif (! File.readable?(path))
        print path, " is unreadable.\n"
      elsif (! File.file?(path))
        if (File.directory?(fname)) then
          next
        else
          print path, " is not regular file.\n"
        end
      else
        IO.foreach(path){|line|
          line=Kconv::toeuc(line)
          if pat =~ line
            print path,": ",line
          end
        }
      end
    end
  # 非再帰的検索
  else
    if (File.directory?(fname)) then
      print fname, " is directory.\n"
    elsif (! File.exist?(fname))
      print fname, " is not found.\n"
    elsif (! File.readable?(fname))
      print fname, " is unreadable.\n"
    elsif (! File.file?(fname))
      print fname, " is not regular file.\n"
    else
      IO.foreach(fname){|line|
        line=Kconv::toeuc(line)
        if pat =~ line
          print fname,": ",line
        end
      }
    end
  end
}

# 無事終了
exit 0
