#!/usr/bin/env ruby
#-*-ruby-*-
require "dpklib/command"
require "dpklib/parsearg"
require "dpklib/resource"

class DpkrbRewritePathProgram < Dpklib::CommandLineProgram
  def start
    opts = Dpklib.parse_args(argv, "r") || usage

    @path_prefix = opts.shift || usage
    @path_prefix = opts[:r] ? @path_prefix : Regexp.quote(@path_prefix)

    usage if opts.empty?
    @find_from_pathes = opts.to_a
    
    finder = Dpklib::ResourceLoader.new(@find_from_pathes)
    path_regexp = %r'#{@path_prefix}([^\s:]+)'
    begin
      while line = stdin.gets
        line.gsub!(path_regexp) { |matched|
          finder.find($1) || matched
        }
        stdout.write line
        stdout.flush
      end
    rescue Interrupt
      abort
    end
  end

  def usage
    die "usage: #{progname} [OPTIONS] PREFIX_OF_PATH FIND_FROM ...
OPTIONS:
  -r: PREFIX_OF_PATH is regular expression.
"
  end
  execute
end #/DpkrbRewritePathProgram
