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

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

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

if (program.script[process.argv[3]] === undefined) {
    console.error(process.argv[2], 'script not found');
    process.exit(3);
}

const cmd = program.script[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]);