#!/bin/bash
#
# Startup script for Mldonkey
#
# Laurent Culioli <laurent@pschit.net>
#
# chkconfig: 345 90 15
# description: Mldonkey is client to access multiple peer-to-peer network
# processname: mlnet
# config: /etc/sysconfig/mldonkey

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

# Source some options 
. /etc/sysconfig/mldonkey
[ -z $LOGFILE ] && LOGFILE="/dev/null"

RETVAL=0

# Path to the mldonkey binary.
mldonkey=/usr/lib/mldonkey/mlnet

# Path to mldonkey home.
mlhome=~mldonkey

# Source networking configuration.
. /etc/sysconfig/network

# Check that networking is up.
[ ${NETWORKING} = "no" ] && exit 0

send_mldonkey_command() {
        # this dosn't work any more :-(
        #PASSWORD=`grep "^ password =" /var/lib/mldonkey/downloads.ini | sed 's/ password = //g'`
        if [ -n "$PASSWORD" ] ; then
                param="--auth $PASSWORD"
        else
                param=""
        fi
        mldonkey_command $param $*
}

log_ok() {
	rc=1
	if [ -n "$LOGFILE" ] ; then
                if [ ! -e $LOGFILE ] ; then
                        touch $LOGFILE
                fi
                chown mldonkey:mldonkey $LOGFILE
		rc=0
        fi
	return $rc
}

start() {
        gprintf "Starting Mldonkey: "
        params="-daemon -run_as_user mldonkey"
        if [ log_ok ] ; then
                params="$params -log_file $LOGFILE"
        fi
        cd $mlhome
        daemon --check mlnet $NICE $mldonkey $params
        touch /var/lock/subsys/mlnet
        echo
}

stop() {
        gprintf "Stopping Mldonkey: "
        #send_mldonkey_command kill
        killproc $mldonkey
        RETVAL=$?
        [ $RETVAL -eq 0 ] && rm -f /var/lock/subsys/mlnet
        echo
}

reload() {
        gprintf "Reloading Mldonkey: "
        killproc $mldonkey -HUP
        echo
}


# See how we were called.
case "$1" in
        start)
                start
                ;;
        stop)
                stop
                ;;
        reload)
                reload
                ;;
        restart)
                stop
                start
                ;;
        pause)
                send_mldonkey_command pause all
                ;;
        resume)
                send_mldonkey_command resume all
                ;;
	reopenlog)
		send_mldonkey_command close_log
		log_ok && send_mldonkey_command log_file $LOGFILE
		;;
        status)
                status mlnet
                send_mldonkey_command vd
                ;;
        *)
                gprintf "Usage: mldonkey {start|stop|restart|reload|pause|resume|reopenlog|status}\n"
                RETVAL=1
esac
exit $RETVAL
