#! /usr/bin/env ruby
# frozen_string_literal: true

require "roby"
require "roby/cli/main"

# 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")

if ARGV.first
    command_name = ARGV.first.tr("-", "_")
    if Roby::CLI::Main.commands.has_key?(command_name)
        begin
            Roby::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

KNOWN_MODES = Hash[
    "gen" => "generate new Roby models / objects within a Roby appplication directory",
    "run" => "start a Roby instance",
    "shell" => "connect to a running Roby instance with a shell",
    "test" => "run tests for this Roby app",
    "autotest" => "run tests for this Roby app continuously",
    "quit" => "ask a running Roby application to quit",
    "restart" => "restart a running Roby application",

    "init" => "create a new Roby app",
    "add-robot" => "deprecated, use roby gen robot instead"
]

if !mode || !KNOWN_MODES.has_key?(mode)
    if mode
        STDERR.puts "unknown mode #{mode}"
    end
    max_mode_length = KNOWN_MODES.keys.map(&:length).max
    format = "%-#{max_mode_length}s %s"
    KNOWN_MODES.each do |mode_name, mode_description|
        STDERR.puts(format(format, mode_name, mode_description))
    end
    exit 1
end

require "roby/app/scripts/#{mode}"
