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

cmd=$1

function usage() {
    echo -e "\n  OpenCanary\n"
    echo -e "\topencanaryd [ --start | --dev | --stop | --restart | --copyconfig | --usermodule | --version | --help ] [--uid=nobody] [--gid=nogroup]\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--version\tDisplays the current opencanary version."
    echo -e "\t\t--"
    echo -e "\t\t--help\tThis help\n"
    echo -e "\toptions"
    echo -e "\t\t--allow-run-as-root\tDo not drop privileges of the opencanary once process starts"
    echo -e "\t\t--uid\tSpecify a user or uid to drop privileges to"
    echo -e "\t\t--gid\tSpecify a group of gid to drop privileges to"
}

# Parse options
for arg in "$@"; do
   case $arg in
        --uid=*)
            readonly TWISTD_UID_FLAG=" --uid=${arg#*=}"
            ;;
        --gid=*)
            readonly TWISTD_GID_FLAG=" --gid=${arg#*=}"
            ;;
    esac
done

function warn_drop_privileges {
  if  [[ -z $TWISTD_UID_FLAG || -z $TWISTD_GID_FLAG ]]; then
      echo "WARNING: OpenCanary will not drop root user or group privileges after launching. Set both --uid=nobody and --gid=nogroup (or another low privilege user/group) to silence this warning." >&2
  fi
}

# Use sudo when not running as root
function sudo() {
  if [ "$EUID" -ne 0 ]; then
    $(which sudo) $*
  else
    # Strip `sudo -E` before running the remaining command
    ${*:2}
  fi
}

if [ "${cmd}" == "--start" ]; then
    warn_drop_privileges
    sudo -E "${DIR}/twistd" -y "${DIR}/opencanary.tac" --pidfile "${PIDFILE}" --syslog --prefix=opencanaryd ${TWISTD_UID_FLAG:-} ${TWISTD_GID_FLAG:-}
elif [ "${cmd}" == "--dev" ]; then
    warn_drop_privileges
    sudo -E "${DIR}/twistd" -noy "${DIR}/opencanary.tac" ${TWISTD_UID_FLAG:-} ${TWISTD_GID_FLAG:-}
elif [ "${cmd}" == "--usermodule" ]; then
  usermodconf=$(python -c "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 -E "${DIR}/twistd" -noy "${DIR}/opencanary.tac"

elif [ "${cmd}" == "--restart" ]; then
    pid=`sudo -E cat "${PIDFILE}"`
    sudo -E kill "$pid"
    warn_drop_privileges
    sudo -E "${DIR}/twistd" -y "${DIR}/opencanary.tac" --pidfile "${PIDFILE}" --syslog --prefix=opencanaryd ${TWISTD_UID_FLAG:-} ${TWISTD_GID_FLAG:-}
elif [ "${cmd}" == "--stop" ]; then
    pid=`sudo -E cat "${PIDFILE}"`
    sudo -E 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=$(python3 -c "from pkg_resources import resource_filename; print(resource_filename('opencanary', 'data/settings.json'))")
    sudo -E mkdir -p /etc/opencanaryd
    sudo -E 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\""
elif [ "${cmd}" == "--version" ]; then
    python -c "from opencanary import __version__; print(__version__);"
else
    usage
    exit 1
fi
