#! /usr/bin/env bash

PATH=/bin:/usr/bin:/sbin:/usr/sbin
PRGNAME=caddy
NAME=caddy
DESC="Caddy Server"
CONF_DIR=/etc/caddy
LOG_DIR=/var/log/caddy
CONF_FILE=$CONF_DIR/Caddyfile
PID_FILE=/var/run/$NAME.pid
DAEMON=/usr/sbin/caddy

if [ ! -x $DAEMON ]; then
  echo "Program not installed or not executable"
  exit 5
fi

# Source function library.
if [ -f /etc/rc.d/init.d/functions ]; then
    . /etc/rc.d/init.d/functions
fi

function isRunning() {
  status -p $PID_FILE $NAME > /dev/null 2>&1
}

function checkUser() {
  if [ `id -u` -ne 0 ]; then
    echo "You need root privileges to run this script"
    exit 4
  fi
}

case "$1" in
  start)
    checkUser
    isRunning
    if [ $? -eq 0 ]; then
      echo "Already running."
      exit 0
    fi

    if [ -n "$MAX_OPEN_FILES" ]; then
      ulimit -n $MAX_OPEN_FILES
    fi

    # Start Daemon
    action $"Starting $DESC: ..." su -s /bin/sh -c "nohup ${DAEMON} run --environ --config ${CONF_FILE} --pidfile ${PID_FILE} >> ${LOG_DIR}/${PRGNAME}.log 2>&1 &"

    return=$?
    if [ $return -eq 0 ]
    then
      sleep 5
      # check if pid file has been written to
      if ! [[ -s $PID_FILE ]]; then
        echo "FAILED"
        exit 1
      fi
      i=0
      timeout=10
      # Wait for the process to be properly started before exiting
      until { cat "$PID_FILE" | xargs kill -0; } >/dev/null 2>&1
      do
        sleep 1
        i=$(($i + 1))
        if [ $i -gt $timeout ]; then
          echo "FAILED"
          exit 1
        fi
      done
    fi

    exit $return
    ;;
  stop)
    checkUser
    echo -n "Stopping $DESC: ..."

    if [ -f "$PID_FILE" ]; then
      killproc -p $PID_FILE -d 20 $NAME
      if [ $? -eq 1 ]; then
        echo  "$DESC is not running but pid file exists, cleaning up"
      elif [ $? -eq 3 ]; then
        PID="`cat $PID_FILE`"
        echo  "Failed to stop $DESC (pid $PID)"
        exit 1
      fi
      rm -f "$PID_FILE"
      echo  ""
      exit 0
    else
      echo  "(not running)"
    fi
    exit 0
    ;;
  status)
    status -p $PID_FILE $NAME
    exit $?
    ;;
  restart)
    if [ -f "$PID_FILE" ]; then
      $0 stop
      sleep 1
    fi
    $0 start
    ;;
  reload)
    if [ -f "$PID_FILE" ]; then
      action $"Reloading $DESC: ..." su -s /bin/sh -c "nohup ${DAEMON} reload --config ${CONF_FILE} --pidfile ${PID_FILE} >> ${LOG_DIR}/${PRGNAME}.log 2>&1 &"
    else
      echo  "$DESC is not running"
    fi
    ;;
  *)
    echo "Usage: $0 {start|stop|restart|reload|status}"
    exit 3
    ;;
esac

