#! /usr/bin/ruby

#==============================================================================#
# $Id: mkexa,v 1.1 2003/11/27 18:37:06 yuya Exp $
#==============================================================================#

require 'getoptlong'
require 'exerb/recipe'

#==============================================================================#

module MakeExaCommand

  OPTIONS = [
    ['--verbose',  '-v', GetoptLong::NO_ARGUMENT, 'enable verbose mode.'],
    ['--help',     '-h', GetoptLong::NO_ARGUMENT, 'display this information.'],
  ]

  def self.main(argv)
    options = self.parse_options(argv)

    if options[:version]
      self.print_version
      exit(1)
    end

    if options[:help] || argv.size < 1
      self.print_usage
      exit(1)
    end

    recipe_file  = argv.shift
    archive_file = self.make_filename(recipe_file, 'exa')

    recipe  = Exerb::Recipe.new_from_file(recipe_file)
    archive = recipe.archive
    archive.write_to_file(archive_file)

    exit(0)
  rescue Exerb::ExerbError => e
    STDERR.puts("exerb: #{e.message}")
    exit(1)
  end

  def self.parse_options(argv)
    options = {}
    config  = OPTIONS.collect { |ary| ary[0, 3] }

    parser = GetoptLong.new
    parser.set_options(*config)
    parser.each_option { |name, argument|
      options[name.sub(/^--/, '').intern] = argument
    }

    options[:verbose]  = !!options[:verbose]
    options[:help]     = !!options[:help]

    return options
  rescue GetoptLong::InvalidOption
    exit(1)
  end

  def self.print_usage
    puts("Exerb #{Exerb::VERSION}")
    puts

    puts("Usage: mkexa [options] recipe-file")
    puts

    puts("Options:")
    OPTIONS.each { |long, short, arg, comment|
      printf("  %s  %-10s  %s\n", short, long, comment)
    }
    puts
  end

  def self.make_filename(filename, extension)
    return filename.sub(/(\.exr$|$)/, '.' + extension)
  end

end

#==============================================================================#

MakeExaCommand.main(ARGV)

#==============================================================================#
#==============================================================================#
