#! /usr/bin/env ruby

# Reset the interrupt handler to the default. An ignored handler is inherited,
# so this makes sure that the Roby app is based on the handler's expected state
trap('INT', 'DEFAULT')

require 'rock/bundle'

# The logs are public by default in bundles, but are private by default in Roby
# (the Roby-oriented scripts must set it to true when needed)
#
# Reset to the Roby default
Roby.app.public_logs = false

require 'syskit/cli/main'

# Transform 'syskit help <mode>' to 'syskit <mode> --help' if mode is not
# handled by thor
if ARGV[0] == 'help'
    if (command_name = ARGV[1])
        if !Syskit::CLI::Main.all_commands.has_key?(command_name)
            ARGV.shift
            ARGV << '--help'
        end
    end
# Transform 'syskit <mode> --help' to 'syskit help <mode>' if mode is handled
# by thor
elsif ['-h', '--help'].include?(ARGV[1])
    STDERR.puts "WARN: syskit <mode> --help is deprecated, use syskit help <mode> instead"
    if Syskit::CLI::Main.all_commands.has_key?(ARGV[0])
        ARGV.unshift 'help'
    end
end

if ARGV.first
    command_name = ARGV.first.tr('-', '_')
    global_help = (command_name == 'help') && (ARGV.size == 1)
    if !global_help && Syskit::CLI::Main.all_commands.has_key?(command_name)
        begin
            Syskit::CLI::Main.start(ARGV)
            exit 0
        rescue Roby::CLI::CLIException => e
            STDERR.puts Roby.color(e.message, :red)
            exit 1
        end
    end
end

ORIGINAL_ARGV = ARGV.dup
mode = ARGV.shift

SYSKIT_MODES = %w[doc ide process_server].freeze
ROBY_MODES = %w[run shell test gen quit restart].freeze
if [nil, '--help', '-h', 'help'].include?(mode)
    thor_modes = Syskit::CLI::Main
                 .all_commands
                 .find_all { |_name, command| !command.hidden? }
                 .map(&:first)
    all_modes = SYSKIT_MODES | ROBY_MODES | thor_modes
    puts "usage: syskit [#{all_modes.sort.join('|')}] <mode-arguments>"
    puts "Run 'syskit help <mode>' for more information"
else
    if SYSKIT_MODES.include?(mode)
        require "syskit/scripts/#{mode}"
    elsif ROBY_MODES.include?(mode)
        require "roby/app/scripts/#{mode}"
    end

    begin
        require "syskit/scripts/#{mode}"
    rescue LoadError => e
        begin
            require "roby/app/scripts/#{mode}"
        rescue LoadError
            STDERR.puts "unknown mode '#{mode}'"
            exit(1)
        end
    end
end
