#!/bin/bash
DIR=$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )
PIDFILE="${DIR}/opencanaryd.pid"

cmd=$1

function usage() {
    echo -e "\n  OpenCanary v1.0\n"
    echo -e "\topencanaryd [ --start | --dev | --stop | --restart | --copyconfig | --usermodule | --help ]\n\n"
    echo -e "\t\t--start\tStarts the opencanaryd process"
    echo -e "\t\t--dev\tRun the opencanaryd process in the foreground"
    echo -e "\t\t--stop\tStops the opencanaryd process"
    echo -e "\t\t--usermodule\tRun opencanaryd in foreground with only usermodules enabled"
    echo -e "\t\t--copyconfig\tCreates a default config file at /etc/opencanaryd/opencanary.conf"
    echo -e "\t\t--"
    echo -e "\t\t--help\tThis help\n"

}

if [ "${cmd}" == "--start" ]; then
    sudo "${DIR}/twistd" -y "${DIR}/opencanary.tac" --pidfile "${PIDFILE}" --syslog --prefix=opencanaryd
elif [ "${cmd}" == "--dev" ]; then
    sudo "${DIR}/twistd" -noy "${DIR}/opencanary.tac"
elif [ "${cmd}" == "--usermodule" ]; then
  usermodconf=$(python -c "from __future__ import print_function; from pkg_resources import resource_filename; print(resource_filename('opencanary', 'data/settings-usermodule.json'))")

  if [ -f opencanary.conf ]; then
    if ! diff -q opencanary.conf "${usermodconf}" 2>&1 >/dev/null; then
      echo "Backing up old config to ./opencanary.conf.old"
      cp opencanary.conf{,.old}
    fi
  fi

  cp "${usermodconf}" opencanary.conf
  sudo "${DIR}/twistd" -noy "${DIR}/opencanary.tac"

elif [ "${cmd}" == "--restart" ]; then
    pid=`sudo cat "${PIDFILE}"`
    sudo kill "$pid"
    sudo "${DIR}/twistd" -y "${DIR}/opencanary.tac" --pidfile "${PIDFILE}" --syslog --prefix=opencanaryd
elif [ "${cmd}" == "--stop" ]; then
    pid=`sudo cat "${PIDFILE}"`
    sudo kill "$pid"
elif [ "${cmd}" == "--copyconfig" ]; then
    if [ -f /etc/opencanaryd/opencanary.conf ]; then
        echo "A config file already exists at /etc/opencanaryd/opencanary.conf, please move it first"
        exit 1
    fi
    defaultconf=$(python -c "from __future__ import print_function; from pkg_resources import resource_filename; print(resource_filename('opencanary', 'data/settings.json'))")
    sudo mkdir -p /etc/opencanaryd
    sudo cp "${defaultconf}" /etc/opencanaryd/opencanary.conf
    echo -e "[*] A sample config file is ready /etc/opencanaryd/opencanary.conf\n"
    echo    "[*] Edit your configuration, then launch with \"opencanaryd --start\""
else
    usage
    exit 1
fi
