#!/bin/bash
#
# rtorrent@###USERNAME###          Start up the rtorrent@user daemon
#
# chkconfig: 2345 55 25
# description: This service starts up the rtorrent@###USERNAME### daemon.
#
# processname: screen rtorrent
# pidfile: /var/www/session/###USERNAME###/rtorrent.pid

### BEGIN INIT INFO
# Provides: rtorrent@###USERNAME###
# Required-Start: $local_fs $network $syslog
# Required-Stop: $local_fs $syslog
# Should-Start: $syslog
# Should-Stop: $network $syslog
# Default-Start: 2 3 4 5
# Default-Stop: 0 1 6
# Short-Description: Start up the rtorrent@###USERNAME### daemon
# Description:       
#                   
### END INIT INFO

USER="###USERNAME###"
NAME="rtorrent@###USERNAME###"
RTORRENT_BIN="###RTORRENT_PATH###/rtorrent"
SCREEN_OPTS="-dmS 'rtorrent@###USERNAME###' ${RTORRENT_BIN}"
SCREEN_BIN="/usr/bin/screen"
RT_LOCK_FILE="/var/www/session/###USERNAME###/rtorrent.lock"
PID_FILE="/var/www/session/###USERNAME###/rtorrent.pid"

# Source function library.
. /etc/init.d/functions


start() {

    local i

    echo "Starting ${NAME}"

    rm -f "${RT_LOCK_FILE}"
    daemon --user "${USER}" ${SCREEN_BIN} ${SCREEN_OPTS}
    i=0
    while true ; do
       i=$((i+1))
       [ ${i} -gt 30 ] && break
       if [ -e "${RT_LOCK_FILE}" ] ; then
           cat "${RT_LOCK_FILE}" | awk -F':' '{print $2}' | sed -e 's/[^0-9]//' > "${PID_FILE}"
           break
       fi
       sleep 2
    done
}

stop() {
    echo "Stopping ${NAME}"

    [ -f "${PID_FILE}" ] \
        && kill $( cat "${PID_FILE}" )
    rm -f "${PID_FILE}"
    rm -f "${RT_LOCK_FILE}"
}



case "$1" in
  start)
    start
    ;;
  stop)
    stop
    ;;
  restart)
    stop
    sleep 5
    start
    ;;
status)
    status -p "${PID_FILE}" "${NAME}"
    ;;
*)
    echo "Usage:  ${0} start|stop|restart|status"
;;
esac

exit 0

