#!/bin/bash

. /etc/rc.conf
. /etc/rc.d/functions
. /etc/conf.d/sabnzbd

PID="$(pgrep -f -u "${SABNZBD_USER}" SABnzbd.py)"

case "${1}" in
  start)
    stat_busy "Starting SABnzbd"

    if [ -f /run/daemons/sabnzbd ]; then
      echo -n "Sabnzbd is already running as a daemon! If you are certain it is not running, remove /run/daemons/sabnzbd."
      stat_fail
    else
      su - "${SABNZBD_USER}" -c "python2 ${SABNZBD_DIR}/SABnzbd.py ${SABNZBD_ARGS}" -s /bin/sh
      if [ "${?}" -gt 0 ]; then
        stat_fail
        exit 1
      else
        add_daemon sabnzbd
        stat_done
      fi
    fi
    ;;
  stop)
    stat_busy "Stopping SABnzbd"

    curl -f "${SABNZBD_PROTOCOL}://${SABNZBD_USPW}${SABNZBD_IP}:${SABNZBD_PORT}/sabnzbd/api?mode=shutdown&apikey=${SABNZBD_KEY}" &> /dev/null

    if [ "${?}" -gt 0 ]; then
      stat_fail
      exit 1
    else
      rm_daemon sabnzbd
      stat_done
    fi
    ;;
  force-stop)
    stat_busy "Stopping SABnzbd (forced)"

    [ -n "${PID}" ]; kill "${PID}" &> /dev/null

    if [ "${?}" -gt 0 ]; then
      stat_fail
      exit 1
    else
      [ -f /run/daemons/sabnzbd ]; rm -f /run/daemons/sabnzbd &> /dev/null
      rm_daemon sabnzbd
      stat_done
    fi
    ;;
  restart)
    "${0}" stop
    sleep 1
    "${0}" start
    ;;
  force-restart)
    "${0}" force-stop
    sleep 1
    "${0}" start
    ;;
  status)
    stat_busy "Checking SABnzbd status";
    ck_status sabnzbd
    ;;
  *)
    echo "usage: ${0} {start|stop|restart|force-stop|force-restart|status}"
esac

exit 0