#!/bin/bash
node="$(which node)"
SRC="$0"
DIR="$(cd $(dirname "$0"); pwd)"
REALSRC="$(readlink "$SRC")"
if [ ! -z $REALSRC ];
  then
    SRC="$(cd $(dirname $DIR/$REALSRC); pwd)"
else
  SRC="$DIR"
fi
pidfile="$SRC/pm2-gui-upgraded.pid"
prefixINFO="\033[1;32m[INFO]\033[0m"
prefixWARN="\033[1;33m[WARN]\033[0m"

function isRunning() {
  if [ ! -f $pidfile ];
    then
      return 0;
  fi
  if [ ! -s $pidfile ];
    then 
      rm $pidfile;
      return 0;
  fi
  if test $(ps -p $(cat $pidfile) | wc -l) -gt 1;
    then 
      return 1;
  fi 
  rm $pidfile;
  return 0;
}

function status() {
  isRunning;
  if [ 0 -eq $? ];
    then
      echo -e "$prefixWARN \033[31m✘ stopped\033[0m";
  else
    echo -e "$prefixINFO \033[32m✔ running\033[0m";
  fi
}

function server (){
  isRunning;
  if [ 0 -eq $? ];
    then
      echo -e "$prefixINFO Starting..."
      $node $SRC/lib/daemon "$@"
      sleep 1;
  fi
  status;
}

function usage () {
  cat <<-EOF

  Usage: $(basename $0) <cmd> [options]

  Commands:
    start [config_file]   start the service, including agent and web server
    agent [config_file]   start the agent only
    stop                  stop the running service
    restart               restart the service
    mon                   run the curses-like dashboard in terminal
    status                show the status of service
    logs [log_directory]  view the logs

  Examples:
    $(basename $0) start
    $(basename $0) start /path/to/my-pm2-gui.ini
    $(basename $0) mon
    $(basename $0) logs
    $(basename $0) logs /path/to/logs

EOF
}

case "$1" in
  start)
    server "$@";  # bash < v4.1 did not support ;&
    ;;
  agent)
    server "$@";
    ;;
  mon)
    $node $SRC/lib/daemon "$@";
    status;
    ;;
  stop)
    isRunning;
    if [ 0 -eq $? ];
      then
        echo -e "$prefixWARN Already stopped.";
    else
      echo -e "$prefixINFO Stopping..."
      kill $(cat $pidfile);
      sleep 1;
      status;
    fi
    ;;

  restart)
    isRunning;
    if [ 0 -eq $? ];
      then
        echo -e "$prefixWARN PID not found, no need to stop anything.";
        $node $SRC/lib/daemon "$@"
    else
      kill -SIGHUP $(cat $pidfile);
    fi
    sleep 1;
    status;
    ;;

  logs)
    out="pm2-gui-upgraded.out";
    err="pm2-gui-upgraded.err";
    dir="$2";
    if [ -z $dir ];
      then
        dir="$SRC/logs" 
        out="$dir/$out";
        err="$dir/$err";
    else
      out="$dir/$out";
      err="$dir/$err";
    fi
    if [ ! -f $out ] && [ ! -f $err ];
      then
        echo -e "$prefixWARN Logs can not be found in directory \033[1m$dir\033[0m.";
    else
      echo -e "$prefixINFO Logs from \033[1m$out\033[0m and \033[1m$err\033[0m:";
      tail -n 20 -F $out $err;
    fi
    ;;

  status)
    status;
    ;;

  *)
    usage "$0";
    exit 1
    ;;
esac