#!/usr/bin/env gjs
// Copyright 2013 Endless Mobile, Inc.

const Format = imports.format;
const System = imports.system;

String.prototype.format = Format.format;

// Other constants, available from subcommands' code
const commandSearchPath = "/usr/libexec/eos-application-manifest/commands";
const programVersion = "0.5.0";

// Import commands from commands/ directory (local first)
imports.searchPath.unshift(commandSearchPath);
imports.searchPath.unshift('./commands');

// Must invoke a subcommand
if (ARGV.length === 0) {
    // automatically invoke "help" command with no arguments
    const Help = imports.help;
    Help.execute([]);
    System.exit(1);
}

let command_name = ARGV.shift();
let command;
try {
    command = imports[command_name];
} catch (e) {
    if (/No JS module '.*' found in search path/.test(e.message)) {
        let program_name = System.programInvocationName;
        printerr("%s: '%s' is not a valid command name. See %s help.".format(
            program_name, command_name, program_name));
        System.exit(1);
    }
}
try {
    command.execute(ARGV);
} catch (e) {
    printerr('%s: %s'.format(System.programInvocationName, e.message));
    System.exit(1);
}
