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

class DpkrbMvgsub < Dpklib::CommandLineProgram
  def start
    opts = Dpklib.parse_args(argv, "cnvipsr") || usage
    @is_dryrun = opts[:n]
    @is_verbose = opts[:v] || @is_dryrun
    is_copy = opts[:c]
    pattern = opts.shift || usage
    replaced = opts.shift || usage
    files = opts.args
    usage if files.empty?

    gsub_proc = if opts[:p]
                  gsub_proc_plain(%r"\A#{Regexp.quote(pattern)}", replaced)
                elsif opts[:s]
                  gsub_proc_plain(%r"#{Regexp.quote(pattern)}\Z", replaced)
                elsif opts[:r]
                  gsub_proc_regexp(Regexp.new(pattern), replaced)
                else
                  gsub_proc_plain(%r"#{Regexp.quote(pattern)}", replaced)
                end
    for file in files
      newname = gsub_proc[file]
      if is_copy
        command("cp", "-a", file, newname)
      else
        command("mv", file, newname)
      end
    end
  end

  def command(*execargs)
    info(execargs.join(" ")) if @is_verbose
    @is_dryrun || system(*execargs)
  end

  def gsub_proc_plain(regexp, replaced)
    proc { |str|
      str.gsub(regexp) {
        replaced
      }
    }
  end

  def gsub_proc_regexp(regexp, replaced)
    proc { |str|
      str.gsub(regexp, replaced)
    }
  end

  def usage
    die "usage: #{progname} [OPTIONS] [MATCHING_MODE] PATTERN REPLACED [FILES ...]
OPTIONS:
  -c: Don't move but copy. 
  -n: dry-run mode. (Do nothing actually.)
  -v: verbose mode.
MATCHING_MODE:
  -i: Inside match. (default)
  -p: Prefix match.
  -s: Suffix match.
  -r: PATTERN is regular expression, and REPLACED contains matched string
      reference ('\\0', '\\1', ..., '\\9').
"
  end
  execute
end #/DpkrbMvgsub
