#! /bin/sh

### BEGIN INIT INFO
# Provides:          couchpotato
# Required-Start:    $local_fs $network $remote_fs
# Required-Stop:     $local_fs $network $remote_fs
# Should-Start:      $NetworkManager
# Should-Stop:       $NetworkManager
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: starts instance of CouchPotato
# Description:       starts instance of CouchPotato using start-stop-daemon
### END INIT INFO

# Check for existance of defaults file
# and utilze if available
if [ -f /etc/default/couchpotato ]; then
    . /etc/default/couchpotato
else
    echo "/etc/default/couchpotato not found using default settings.";
fi

# Script name
NAME=couchpotato

# App name
DESC=CouchPotato

# Path to app root
CP_APP_PATH=${APP_PATH-/usr/local/sbin/CouchPotatoServer/}

# User to run CP as
CP_RUN_AS=${RUN_AS-root}

# Path to python bin
CP_DAEMON=${DAEMON_PATH-/usr/bin/python}

# Path to store PID file
CP_PID_FILE=${PID_FILE-/var/run/couchpotato.pid}

# Other startup args
CP_DAEMON_OPTS=" CouchPotato.py --daemon --pid_file=${CP_PID_FILE}"

test -x $CP_DAEMON || exit 0

set -e

case "$1" in
  start)
        echo "Starting $DESC"
        rm -rf $CP_PID_FILE || return 1
        touch $CP_PID_FILE
        chown $CP_RUN_AS $CP_PID_FILE
        start-stop-daemon -d $CP_APP_PATH -c $CP_RUN_AS --start --background --pidfile $CP_PID_FILE --exec $CP_DAEMON -- $CP_DAEMON_OPTS
        ;;
  stop)
        echo "Stopping $DESC"
        start-stop-daemon --stop --pidfile $CP_PID_FILE --retry 15
        ;;

  restart|force-reload)
        echo "Restarting $DESC"
        start-stop-daemon --stop --pidfile $CP_PID_FILE --retry 15
        start-stop-daemon -d $CP_APP_PATH -c $CP_RUN_AS --start --background --pidfile $CP_PID_FILE --exec $CP_DAEMON -- $CP_DAEMON_OPTS
        ;;
  *)
        N=/etc/init.d/$NAME
        echo "Usage: $N {start|stop|restart|force-reload}" >&2
        exit 1
        ;;
esac

exit 0
