#!/usr/bin/env node

var program = require('commander');
var spawn = require('child_process').spawn;
var fs = require('fs');

let suite;

program
  .description('Run the tests for the current suite or the provided one.')
  .arguments('[suite]')
  .option('--headless', 'Run in headless mode.')
  .action((suiteArg) => suite = suiteArg)
  .parse(process.argv);

let args = [];
const ENVIRONMENT_FILENAME = '.suite'; // This file is created by the start command.

if (suite) {
  if (fs.existsSync(ENVIRONMENT_FILENAME) && suite != fs.readFileSync(ENVIRONMENT_FILENAME)) {
    console.error('You cannot test a suite while another one is running. If you want to test the current suite, ' +
                  'do not provide the suite argument. Otherwise, stop the current suite and run the command again.');
    process.exit(1);
  }
  console.log('Suite %s provided. Running test related to this suite against built version of Authelia.', suite);
  args.push('test/suites/' + suite + '/test.ts');
}
else if (fs.existsSync(ENVIRONMENT_FILENAME)) {
  suite = fs.readFileSync(ENVIRONMENT_FILENAME);
  console.log('Suite %s detected from dev env. Running test related to this suite.', suite);
  args.push('test/suites/' + suite + '/test.ts');
}
else {
  console.log('No suite provided therefore all suites will be tested.');
  args.push('test/suites/**/test.ts');
}

mocha = spawn('./node_modules/.bin/mocha', ['--forbid-only', '--forbid-pending', '--exit', '--colors', '--require', 'ts-node/register', ...args], {
  env: {
    ...process.env,
    TS_NODE_PROJECT: 'test/tsconfig.json',
    HEADLESS: (program.headless) ? 'y' : 'n',
  }
});

mocha.stdout.pipe(process.stdout);
mocha.stderr.pipe(process.stderr);

mocha.on('exit', function(statusCode) {
  if (statusCode != 0) {
    console.error("The tests failed... Mocha exited with status code " + statusCode);
    fs.readFile('/tmp/authelia-server.log', function(err, data) {
      if (err) {
        console.error(err);
        return;
      }
      console.log(data.toString('utf-8'));
    });
  }
  process.exit(statusCode);
})