#!/usr/bin/env node

var program = require('commander');
var execSync = require('child_process').execSync;
var spawn = require('child_process').spawn;
var fs = require('fs');
 
program
  .option('-c, --config <config>', 'Configuration file to run Authelia with.')
  .option('--no-watch', 'Disable hot reload.')
  .parse(process.argv);

let config = 'config.yml'; // set default config file.

if (program.config) {
  config = program.config;
}

// Render the production version of the nginx portal configuration
execSync('./example/compose/nginx/portal/render.js --production');

// Prepare the environment
execSync('./scripts/utils/prepare-environment.sh');

var server;
if (program.watch) {
  server = spawn('./node_modules/.bin/nodemon',
    ['-e', 'yml', '--ignore', './users_database*.yml', '--exec', `node dist/server/src/index.js ${config}`]);
}
else {
  server = spawn('/usr/bin/env', ['node', 'dist/server/src/index.js', config]);
}

var logStream = fs.createWriteStream('/tmp/authelia-server.log', {flags: 'a'});

server.stdout.on('data', (data) => {
  process.stdout.write(`${data}`);
});
server.stdout.pipe(logStream);

server.stderr.on('data', (data) => {
  process.stderr.write(`${data}`);
});
server.stderr.pipe(logStream);