if (process.argv.length < 3) {
    console.error('Not enough arguments');
    process.exit();
}

const programs = require('./deploy.json').programs;

let program = null;
let list = [];
programs.forEach(elt => {
    list.push(elt.name);
    if (elt.name === process.argv[2]) {
        program = elt;
    }
});
if (program === null) {
    console.error(process.argv[2], 'not found');
    console.error('Available programs:');
    list.forEach(elt => {
        console.error('  ' + elt);
    });
    process.exit();
}

let cmd = ['node', program.main];
if (process.argv.length !== 3) {
    if (program.scripts[process.argv[3]] === undefined) {
        console.error(process.argv[2], 'script not found');
        process.exit();
    }
    cmd = program.scripts[process.argv[3]].split(' ');
}

let argv = [];
argv.push(process.argv[0]);
argv.push(process.argv[1].replace('main.js', cmd[1]));
let longParam = false;
let param = '';
for (let i = 2; i < cmd.length; i++) {
    if (longParam) {
        param += ' ' + cmd[i];
        if (cmd[i][cmd[i].length - 1] === '"') {
            argv.push(param.replace(/^"+|"+$/g, ''));
            param = '';
            longParam = false;
        }
    } else if (cmd[i][0] === '"') {
        longParam = true;
        param = cmd[i];
    } else {
        argv.push(cmd[i]);
    }
}

process.argv = argv;
require('./' + cmd[1]);
