#!/usr/bin/env ruby

at_exit { exit }

command = ARGV.shift if %w(generate destroy update).include?(ARGV[0])

%w(rubygems merb-core).each do |file|
  require file
end

# start merb
Merb.start :environment => 'development', :log_level => 'error'

# remove dependency
module Kernel
  undef dependency if defined?(Kernel.dependency)
end

%w(rubigen rubigen/scripts/generate rubigen/scripts/destroy 
    rubigen/scripts/update fileutils find merb-gen).each do |file|
  require file
end

app_help = <<-EOF
  Application Generators:
  To generate an application use one of the following
  merb-gen app app_name             (for a standard application)
  merb-gen app app_name --flat      (for a flattened application)
  merb-gen app app_name --very-flat (for a single file application)
  merb-gen plugin plugin_name   (creates a plugin gem skeleton)

  Other Generators:
  merb-gen generators
  with no args will display all availble generators for the current configuration.
EOF

# merb-gen || merb-gen help || merb-gen help app || merb-gen app
if ARGV.empty? || (ARGV[0] == "help" && ARGV.length == 1) || 
  (ARGV[0] == "help" && ARGV[1] == "app") || (ARGV[0] == "app" && ARGV.length == 1)
  puts app_help
  
# merb-gen generators
elsif ARGV[0] == "generators"
  # List all the Available Generators
  RubiGen::Base.use_component_sources! Merb.generator_scope
  RubiGen::Scripts::Generate.new.run([])
 
# merb-gen help foo
elsif ARGV[0] && ARGV[0] == "help"
  begin
    RubiGen::Base.use_component_sources! Merb.generator_scope
    RubiGen::Base.lookup(ARGV[1])
    Merb::ComponentGenerator.run ARGV[1], ARGV[2..-1], ARGV[1], command || "generate"
  rescue RubiGen::GeneratorError
    # List all the Available Generators
    RubiGen::Base.use_component_sources! Merb.generator_scope
    RubiGen::Scripts::Generate.new.run([]) 
  rescue => e
    puts e.message
  end

# merb-gen app myapp
elsif ARGV[0] && ARGV[0] == "app" && ARGV[1] && ARGV[1] !~ /^-/
  app_type = case ARGV[2]
  when "--flat"
    "merb_flat"
  when "--very-flat"
    "merb_very_flat"
  else
    "merb"
  end
  Merb::ApplicationGenerator.run ARGV[1], ARGV[3..-1], app_type, command || "generate"
      
# merb-gen plugin foo
elsif ARGV[0] && ARGV[0] == "plugin"
  Merb::ApplicationGenerator.run ARGV[1], ARGV[2..-1], "merb_plugin", command || "generate"

# merb-gen controller foo
# merb-gen resource foo --test
elsif ARGV[1] && ARGV[1] !~ /^-/
  Merb::ComponentGenerator.run ARGV[1], ARGV[1..-1], ARGV.first, command || "generate"

# catch all merb-gen -??? and display help instead of creating application in -???
elsif ARGV[0] && ARGV[0] =~ /^-/
  puts app_help

else
  begin
    # May be a generator that takes no arguments.
    RubiGen::Base.use_component_sources! Merb.generator_scope
    RubiGen::Base.lookup(ARGV[0])
    Merb::ComponentGenerator.run ARGV[0], ARGV[1..-1], ARGV.first, command || "generate"
  rescue RubiGen::GeneratorError
    puts app_help
  rescue => e
    puts e.message
  end  
end
