# Tiny Tiny eRuby --- command mode module
# 	Copyright (c) 1999-2000,2002 Masatoshi SEKI 
#       You can redistribute it and/or modify it under the same term as Ruby.

module ERbModule
  def ARGV.switch
    return nil if self.empty?
    arg = self.shift
    return nil if arg == '--'
    if arg =~ /^-(.)(.*)/
      return arg if $1 == '-'
      raise 'unknown switch "-"' if $2.index('-')
      self.unshift "-#{$2}" if $2.size > 0
      "-#{$1}"
    else
      self.unshift arg
      nil
    end
  end

  def ARGV.req_arg
    self.shift || raise('missing argument')
  end

  def run(factory)
    begin
      while switch = ARGV.switch
	case switch
	when '-x'			# ruby source
	  output = true
	when '-n'			# line number
	  number = true
	when '-v'			# verbose
	  $VERBOSE = true
	when '--version'		# version
	  STDERR.puts factory.version
	  exit
	when '-d', '--debug'	# debug
	  $DEBUG = true
	when '-r'			# require
	  require ARGV.req_arg
	when '-S'			# sacurity level
	  arg = ARGV.req_arg
	  raise "invalid security level #{arg.dump}" unless arg =~ /^[0-4]$/
	  safe_level = arg.to_i
	when '-T'			# trim mode
	  arg = ARGV.req_arg
	  raise "invalid trim mode #{arg.dump}" unless arg =~ /^[0-2]$/
	  trim_mode = arg.to_i
	else
	  raise "unknown switch #{switch.dump}"
	end
      end
    rescue    			# usage
      STDERR.puts $!.to_s
      STDERR.puts File.basename($0) + 
	" -x -n -v -d -r module -S [0-4] -T [0-2] [--] [file]"
      exit 1
    end

    src = $<.read
    exit 2 unless src
    erb = factory.new(src, safe_level, trim_mode)
    if output
      if number
	l = 1
	for line in erb.src
	  puts "%3d %s"%[l, line]
	  l += 1
	end
      else
	puts erb.src
      end
    else
      erb.run
    end
  end
  module_function :run
end
