const { spawn } = require('child_process');

module.exports = function process(cmd, args, timeout) {
  return new Promise(resolve => {
    const child = spawn(cmd, args, { shell: true });
    let stdout = '', stderr = '';
    let killed = false;

    child.stdout.on('data', d => stdout += d);
    child.stderr.on('data', d => stderr += d);

    const timer = setTimeout(() => {
      killed = true;
      child.kill('SIGKILL');
    }, timeout);

    child.on('close', code => {
      clearTimeout(timer);
      if (killed) return resolve({ status: 'timeout' });
      if (code !== 0) return resolve({ status: 'error', error: stderr || stdout || `Exit code ${code}` });
      resolve({ status: 'success', stdout, stderr });
    });

    child.on('error', err => {
      clearTimeout(timer);
      resolve({ status: 'error', error: err.message });
    });
  });
};