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

class DpkrbGetoptsProgram < Dpklib::CommandLineProgram
  OPTSPEC_AND_ARGS_SEPARATOR = "::"
  OPT_PREFIX = "OPT_"
  OPTVAL_PREFIX = "VAL_"

  def start
    args = argv
    getopts_specs = []
    while true
      arg = args.shift || usage
      break if arg == OPTSPEC_AND_ARGS_SEPARATOR
      getopts_specs << arg
    end
    args_to_parse = args
    usage if getopts_specs.empty?
    
    if opts = Dpklib.parse_args(args_to_parse, *getopts_specs)
      puts_setexpr_opt("USAGE", "false")
      opts.each_options { |optname, optval|
        puts_setexpr_opt(optname, optval ? "true" : "false")
        if optval.kind_of?(String)
          puts_setexpr_optval(optname, optval)
        end
      }
      puts_setexpr_opt("SHIFT", args_to_parse.size - opts.size)
    else
      puts_setexpr_opt("USAGE", "true")
    end
  end

  def puts_setexpr_optval(optname, val)
    puts_setexpr_opt("#{OPTVAL_PREFIX}#{optname}", val)
  end

  def puts_setexpr_opt(optname, val)
    puts_setexpr("#{OPT_PREFIX}#{optname}", val)
  end

  def puts_setexpr(name, val)
    name = convert_to_sh_varname(name)
    stdout.puts %Q'#{name}="#{Dpklib.quote_shell(val.to_s)}"'
  end

  def convert_to_sh_varname(optname)
    optname.gsub("-", "_")
  end
    
  def usage
  die(<<-EOF)
usage: #{progname} ( SINGLE_OPT_SPEC | '' ) [LONG_OPT_SPEC  ...] #{OPTSPEC_AND_ARGS_SEPARATOR} ARGS ...
example:
    eval `dpkruby-getopts 'e' 'g:' :: "$@"`
    $OPT_USAGE && exec echo "usage: ..." 1>&2
    shift $OPT_SHIFT
    $OPT_e && echo "You specified -e."
    $OPT_g && echo "You specified -g with argument $OPT_VAL_g."
    echo "Arguments are following:"
    for arg; do
      echo "  $arg"
    done
  EOF
  end

  execute
end #/DpkrbGetoptsProgram
