const { spawn } = require('child_process');
var stdinString = "";
process.stdin.on('data', function (chunk) {
    stdinString += chunk;
});

process.stdin.on('end', function () {
    var stdinData = JSON.parse(stdinString);
    var handler = stdinData.handler;
    var handlerArg = stdinData.args;
    var handlerWorkDir = stdinData.workDir;
    var prependPath = stdinData.prependPath;

    console.log("##vso[task.debug]Handler: " + handler);
    console.log("##vso[task.debug]HandlerArg: " + handlerArg);
    console.log("##vso[task.debug]HandlerWorkDir: " + handlerWorkDir);
    Object.keys(stdinData.environment).forEach(function (key) {
        console.log("##vso[task.debug]Set env: " + key + "=" + stdinData.environment[key].toString().replace(/\r/g, '%0D').replace(/\n/g, '%0A'));
        process.env[key] = stdinData.environment[key];
    });

    var currentPath = process.env['PATH'];
    var options = {
        stdio: 'inherit',
        cwd: handlerWorkDir
    };
    if (process.platform == 'win32') {
        options.argv0 = `"${handler}"`;
        options.windowsVerbatimArguments = true;

        if (prependPath && prependPath.length > 0) {
            if (currentPath && currentPath.length > 0) {
                process.env['PATH'] = prependPath + ';' + currentPath;
            }
            else {
                process.env['PATH'] = prependPath;
            }
        }
    }
    else {
        if (prependPath && prependPath.length > 0) {
            if (currentPath && currentPath.length > 0) {
                process.env['PATH'] = prependPath + ':' + currentPath;
            }
            else {
                process.env['PATH'] = prependPath;
            }
        }
    }

    if (prependPath && prependPath.length > 0) {
        console.log("##vso[task.debug]Prepend Path: " + process.env['PATH']);
    }

    process.env['TF_BUILD'] = 'True';
    console.log("##vso[task.debug]Handler Setup Complete");
    var launch = spawn(handler, [handlerArg], options);
    launch.on('exit', function (code) {
        console.log("##vso[task.debug]Handler exit code: " + code);
        if (code != 0) {
            process.exit(code);
        }
    });
});
