#!/bin/sh
#
# deluged   deluge bittorrent daemon
#
# chkconfig: - 90 10
# description:  Deluge daemon process handles \
#       all the bittorrent activity. \
#       The Deluge daemon is able to run on \
#       headless machines with the user-interfaces \
#       being able to connect remotely from any platform
# processname: deluged
# pidfile: /var/run/deluged/deluged.pid

# Do not load RH compatibility interface.
WITHOUT_RC_COMPAT=1

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

PORT=58846
STORAGE=/var/spool/deluged
RUNWEBUI=0
WEBPORT=8112
SSL=0

SourceIfNotEmpty /etc/sysconfig/deluged

USER=_deluge
PIDDIR=/var/run/deluged
PIDDMN=$PIDDIR/deluged.pid
PIDWEB=$PIDDIR/deluge-web.pid
LOCKDIR=/var/lock/subsys
LOCKDMN=$LOCKDIR/deluged
LOCKWEB=$LOCKDIR/deluge-web

RETVAL=0

start()
{
    if [ ! -d "$PIDDIR" ]; then
        mkdir -p "$PIDDIR";
        chown root:"$USER" "$PIDDIR"
        chmod 775 "$PIDDIR"
    fi

    start_daemon --pidfile "$PIDDMN" --lockfile "$LOCKDMN" --set-user "$USER" \
        --name deluged --announce -- deluged \
        -c "$STORAGE/.deluge/" -p "$PORT" \
        -l "$STORAGE/.deluge/deluged.log" -P "$PIDDMN"
    RETVAL=$?

    if [ "$RUNWEBUI" = 1 -a -x "/usr/bin/deluge-web" ]; then
        if [ "$SSL" = 1 ]; then
            SSL="--ssl"
        else
            SSL="--no-ssl"
        fi
        start_daemon --lockfile "$LOCKWEB" --set-user "$USER" \
            --announce -- deluge-web \
            -c "$STORAGE/.deluge/" -l "$STORAGE/.deluge/deluge-web.log" \
            -p "$WEBPORT" -f $SSL
    fi

    return $RETVAL
}

stop()
{
    stop_daemon --pidfile "$PIDDMN" --lockfile "$LOCKDMN" --expect-user "$USER" \
        --name deluged -- python
    RETVAL=$?
    if [ "$RUNWEBUI" = 1 -a -x "/usr/bin/deluge-web" ]; then
        stop_daemon --lockfile "$LOCKWEB" --expect-user "$USER" \
            --displayname "deluge-web" -- python
    fi

    return $RETVAL
}

restart()
{
    stop
    start
}

# See how we were called.
case "$1" in
    start)
        start
        ;;
    stop)
        stop
        ;;
    restart)
        restart
        ;;
    condstop)
        if [ -e "$LOCKDMN" ]; then
            stop
        fi
        ;;
    condrestart)
        if [ -e "$LOCKDMN" ]; then
            restart
        fi
        ;;
    status)
        status --pidfile "$PIDDMN" --expect-user "$USER" --name deluged -- python
        RETVAL=$?
        if [ "$RUNWEBUI" = 1 -a -x "/usr/bin/deluge-web" ]; then
            status --displayname deluge-web --expect-user "$USER" -- python
        fi
        ;;
    *)
        msg_usage "${0##*/} {start|stop|restart|condstop|condrestart|status}"
        RETVAL=1
esac

exit $RETVAL
