#!/bin/sh

':' // Hack to pass parameters to Node before running this file
':' //; [ -f ~/.pm2/custom_options.sh ] && . ~/.pm2/custom_options.sh || : ; exec "`command -v nodejs || command -v node`" $PM2_NODE_OPTIONS "$0" "$@"

var commander = require('commander');
var fs        = require('fs');
var path      = p = require('path');
var util      = require('util');
var watch     = require('watch');
var cronJob   = require('cron').CronJob;

var Monit     = require('../lib/Monit');
var UX        = require('../lib/CliUx');
var Log       = require('../lib/Log');
var Satan     = require('../lib/Satan');
var CLI       = require('../lib/CLI');
var cst       = require('../constants.js');
var pkg       = require('../package.json');

commander.version(pkg.version)
  .option('-v --verbose', 'verbose level')
  .option('-s --silent', 'throw less messages', false)
  .option('-m --mini-list', 'display a compacted list without formatting')
  .option('-f --force', 'force actions')
  .option('-n --name <name>', 'set a <name> for script')
  .option('-i --instances <number>', 'launch [number] instances (for networked app)(load balanced)')
  .option('-o --output <path>', 'specify out log file')
  .option('-e --error <path>', 'specify error log file')
  .option('-p --pid <pid>', 'specify pid file')
  .option('-x --execute-command', 'execute a program using fork system')
  .option('-u --user <username>', 'define user when generating startup script')
  .option('-c --cron <cron_pattern>', 'restart a running process based on a cron pattern')
  .option('-w --write', 'write configuration in local folder')
  .option('--interpreter <interpreter>', 'the interpreter pm2 should use for executing app (bash, python...)')
  .option('--no-daemon', "run pm2 daemon in the foreground if it doesn't exist already")
  .option('--node-args <node_args>', "space delimited arguments to pass to node in cluster mode - e.g. --node-args=\"--debug=7001 --trace-deprecation\"",
      function(val) {
          return val.split(' ');
          })
  .usage('[cmd] app');

//
// Start daemon if it does not exist
//
// Function checks if --no-daemon option is present,
// and starts daemon in the same process if it does
//
;(function launchDaemon() {
  commander.parse(process.argv);
  Satan.start(!commander.daemon);
})();

//
// Helper function to fail when unknown command arguments are passed
//
function failOnUnknown(fn) {
  return function(arg) {
    if (arguments.length > 1) {
      console.log(cst.PREFIX_MSG + '\nUnknown command argument: ' + arg);
      commander.outputHelp();
      process.exit(cst.ERROR_EXIT);
    }
    return fn.apply(this, arguments);
  }
}

//
// Start command
//
commander.command('start <script|json_file|stdin(-)>')
  .description('start specific processes')
  .action(function(cmd) {
    if (cmd == "-") {
      process.stdin.resume();
      process.stdin.setEncoding('utf8');
      process.stdin.on('data', function (cmd) {
        process.stdin.pause();
        CLI.startFromJson(cmd, 'pipe');
      });
    } else if (cmd.indexOf('.json') > 0)
      CLI.startFromJson(cmd, 'file');
    else
      CLI.startFile(cmd,'file');
  });

//
// Stop specific id
//
commander.command('stop <pm2_id|name|all|json_file|stdin(-)>')
  .description('stop specific process pm2 id or script name (set with --name or script name)')
  .action(function(param) {
    UX.processing.start();

    if (param == "-") {
      process.stdin.resume();
      process.stdin.setEncoding('utf8');
      process.stdin.on('data', function (param) {
        process.stdin.pause();
        CLI.actionFromJson('stopProcessName', param, 'pipe');
      });
    } else if (param.indexOf('.json') > 0)
      CLI.actionFromJson('stopProcessName', param, 'file');
    else if (param == 'all')
      CLI.stopAll();
    else if (isNaN(parseInt(param))) {
      CLI.stopProcessName(param);
    } else {
      console.log(cst.PREFIX_MSG + 'Stopping process by id ' + param);
      CLI.stopId(param);
    }
  });

//
// Stop All processes
//
commander.command('restart <pm2_id|name|all|json_file|stdin(-)>')
  .description('restart processes by id/name/all or by apps defined in json file')
  .action(function(param) {
    UX.processing.start();

    if (param == "-") {
      process.stdin.resume();
      process.stdin.setEncoding('utf8');
      process.stdin.on('data', function (param) {
        process.stdin.pause();
        CLI.actionFromJson('restartProcessName', param, 'pipe');
      });
    } else if (param.indexOf('.json') > 0)
      CLI.actionFromJson('restartProcessName', param, 'file');
    else if (param == 'all')
      CLI.restartAll();
    else if (isNaN(parseInt(param))) {
      console.log(cst.PREFIX_MSG + 'Restarting process by name ' + param);
      CLI.restartProcessByName(param);
    } else {
      console.log(cst.PREFIX_MSG + 'Restarting process by id ' + param);
      CLI.restartProcessById(param);
    }
  });

//
// Reload process(es)
//
commander.command('reload <name|all>')
  .description('reload all processes or by name')
  .action(function(pm2_id) {
    UX.processing.start();
    if (pm2_id == 'all')
      CLI.reload('reloadProcessId');
    else
      CLI.reloadProcessName(pm2_id, 'reloadProcessId');
  });

//
// Reload process(es)
//
commander.command('gracefulReload <name|all>')
  .description('reload all processes or by name. Will send a "shutdown" message for graceful exit.')
  .action(function(pm2_id) {
    UX.processing.start();
    if (pm2_id == 'all')
      CLI.reload('softReloadProcessId');
    else
      CLI.reloadProcessName(pm2_id, 'softReloadProcessId');
  });

//
// Stop and delete a process by name from database
//
commander.command('delete <name|id|script|all|json_file|stdin(-)>')
  .description('stop and delete a process by name from PM2 database')
  .action(function(name) {
    if (name == "-") {
      process.stdin.resume();
      process.stdin.setEncoding('utf8');
      process.stdin.on('data', function (param) {
        process.stdin.pause();
        CLI.deleteProcess(param, 'pipe');
      });
    } else
      CLI.deleteProcess(name,'');
  });

//
// Send system signal to process
//
commander.command('sendSignal <signal> <pm2_id|name>')
  .description('send a system signal to the process')
  .action(function(signal, pm2_id) {
    UX.processing.start();

    if (isNaN(parseInt(pm2_id))) {
      console.log(cst.PREFIX_MSG + 'Sending signal to process name ' + pm2_id);
      CLI.sendSignalToProcessName(signal, pm2_id);
    } else {
      console.log(cst.PREFIX_MSG + 'Sending signal to process id ' + pm2_id);
      CLI.sendSignalToProcessId(signal, pm2_id);
    }
  });

//
// Stop and delete a process by name from database
//
commander.command('ping')
  .description('ping pm2 daemon - if not up it will launch it')
  .action(failOnUnknown(CLI.ping));

//
// Interact
//
commander.command('interact <secret_key> <machine_name>')
  .description('launch interaction daemon')
  .action(CLI.interact);

commander.command('killInteract')
  .description('launch interaction daemon')
  .action(failOnUnknown(CLI.interactKill));

//
// Web interface
//
commander.command('web')
  .description('launch process/server monit api on ' + cst.WEB_INTERFACE)
  .action(failOnUnknown(function() {
    console.log('Launching web interface on port ' + cst.WEB_INTERFACE);
    CLI.web();
  }));

//
// Save processes to file
//
commander.command('dump')
  .description('dump all processes for resurecting them later')
  .action(failOnUnknown(function() {
    console.log(cst.PREFIX_MSG + 'Dumping processes');
    UX.processing.start();
    CLI.dump();
  }));

//
// Save processes to file
//
commander.command('resurrect')
  .description('resurect previously dumped processes')
  .action(failOnUnknown(function() {
    console.log(cst.PREFIX_MSG + 'Resurrecting');
    UX.processing.start();
    CLI.resurrect();
  }));

//
// Set pm2 to startup
//
commander.command('startup <platform>')
  .description('auto resurect process at startup. [platform] can be centos redhat or ubuntu')
  .action(function(platform) {
    CLI.startup(platform);
  });


//
// Sample generate
//
commander.command('generate <name>')
  .description('generate sample JSON')
  .action(function(name) {
    CLI.generateSample(name);
  });

//
// List command
//
commander.command('list')
  .description('list all processes')
  .action(failOnUnknown(CLI.list));

commander.command('ls')
  .description('(alias) list all processes')
  .action(failOnUnknown(CLI.list));

commander.command('l')
  .description('(alias) list all processes')
  .action(failOnUnknown(CLI.list));

commander.command('status')
  .description('(alias) list all processes')
  .action(failOnUnknown(CLI.list));


// List in raw json
commander.command('jlist')
  .description('list all processes in JSON format')
  .action(failOnUnknown(function() {
    CLI.jlist();
  }));

// List in prettified Json
commander.command('prettylist')
  .description('print json in a prettified JSON')
  .action(failOnUnknown(function() {
    CLI.jlist(true);
  }));

//
// Monitoring command
//
commander.command('monit')
  .description('launch termcaps monitoring')
  .action(failOnUnknown(CLI.monit));

commander.command('m')
  .description('(alias) launch termcaps monitoring')
  .action(failOnUnknown(CLI.monit));

//
// Flushing command
//
commander.command('flush')
  .description('flush logs')
  .action(failOnUnknown(function() {
    CLI.flush();
  }));

//
// Log streaming
//
commander.command('logs [id|name]')
  .description('stream logs file. Default stream all logs')
  .action(function(id) {
    CLI.streamLogs(id);
  });


//
// Kill
//
commander.command('kill')
  .description('kill daemon')
  .action(failOnUnknown(function(arg) {
    CLI.killDaemon();
  }));

//
// Catch all
//
commander.command('*')
  .action(function() {
    console.log(cst.PREFIX_MSG + '\nCommand not found');
    commander.outputHelp();
    process.exit(cst.ERROR_EXIT);
  });

//
// Display help
//
if (process.argv.length == 2) {
  commander.parse(process.argv);
  commander.outputHelp();
  process.exit(cst.ERROR_EXIT);
}


//
// Wait Satan is connected to God to launch parsing
//
// This message is triggered once the RPC Client is connected to the Daemon
// in file Satan.js, method Satan.launchRPC
//
process.on('satan:client:ready', function() {
  commander.parse(process.argv);
  // if (commander.silent) {
  //   global.console = {};
  //   global.console.log = function(){};
  //   global.console.error = function(){};
  // }
});

//
// Init
//
(function init() {
  fs.exists(cst.DEFAULT_FILE_PATH, function(exist) {
    if (!exist) {
      console.log('Initializing folder for pm2 on %s', cst.DEFAULT_FILE_PATH);
      fs.mkdirSync(cst.DEFAULT_FILE_PATH);
      fs.mkdirSync(cst.DEFAULT_LOG_PATH);
      fs.mkdirSync(cst.DEFAULT_PID_PATH);
    }
  });

  /**
   * Create configuration file if not present
   */
  fs.exists(cst.PM2_CONF_FILE, function(exist) {
    if (!exist) {
      console.log('Creating PM2 configuration file in %s', cst.PM2_CONF_FILE);
      fs
        .createReadStream(path.join(__dirname, cst.SAMPLE_CONF_FILE))
        .pipe(fs.createWriteStream(cst.PM2_CONF_FILE));
    }
  });
})();

(function testHarmony() {
  //
  // Harmony test
  //
  try {
    var assert = require('assert')
    , s = new Set();
    s.add('a');
    assert.ok(s.has('a'));
    console.log('● ES6 mode'.green);
  } catch(e) {}
})();
