#!/bin/sh

# Package
PACKAGE="rutorrent"
DNAME="Rutorrent"

# Others
INSTALL_DIR="/usr/local/${PACKAGE}"
PATH="${INSTALL_DIR}/sbin:${INSTALL_DIR}/bin:/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin:/usr/syno/sbin:/usr/syno/bin"
RUNAS="rutorrent"
SYNO3APP="/usr/syno/synoman/webman/3rdparty" 

start_daemon ()
{
    ${INSTALL_DIR}/etc/init.d/S80lighttpd start
    ${INSTALL_DIR}/etc/init.d/S99rtorrent start
    sleep 5
#    ln -s ${INSTALL_DIR}/app ${SYNO3APP}/${PACKAGE} 
}

stop_daemon ()
{
#    rm -f /usr/syno/synoman/webman/3rdparty/rutorrent
    ${INSTALL_DIR}/etc/init.d/S80lighttpd stop
    ${INSTALL_DIR}/etc/init.d/S99rtorrent stop
    sleep 5
}
getsession() {
    session=`awk '/^[[:space:]]*session[[:space:]]*=[[:space:]]*/{print($3)}' "$config"`
    echo $session
}

daemon_status ()
{
    config="/usr/local/rutorrent/etc/rtorrent.conf"
    session=`getsession "$config"`
    if [ -f ${session}/rtorrent.lock ] ; then
        pid=`cat ${session}/rtorrent.lock | awk -F: '{print($2)}' | sed "s/[^0-9]//g"`
	if [ -d /proc/${pid} ]; then
            if [ -f /var/run/lighttpd.pid ] && [ -d /proc/`cat /var/run/lighttpd.pid` ] ; then
    	        return 0
    	    fi
        fi
    fi
    return 1
}

case $1 in
    start)
        if daemon_status
        then
            echo ${DNAME} is already running
            exit 0
        else
            echo Starting ${DNAME} ...
            start_daemon
            exit $?
        fi
        ;;
    stop)
        if daemon_status
	then
            echo Stopping ${DNAME} ...
            stop_daemon
            exit $?
        else
            echo ${DNAME} is not running
            exit 0
        fi
        ;;
    restart)
        stop_daemon
        start_daemon
        exit $?
        ;;
    reload)
        if daemon_status
        then
        stop_daemon
        start_daemon
        fi
        exit $?
        ;;
    status)
        if daemon_status
	then
            echo ${DNAME} is running
            exit 0
        else
            echo ${DNAME} is not running
            exit 1
        fi
        ;;
    log)
        echo $LOGFILE
        exit 0
        ;;
    *)
        exit 1
        ;;
esac

