#!/bin/sh
#
# Startup script for MLDonkey
#
# Leszek Krupinski <leafnode@pld.org.pl>
#
# Based on script by:
# Laurent Culioli <laurent@pschit.net>
#
# chkconfig:	2345 90 15
# description:	MLDonkey is client to access multiple peer-to-peer network
# processname:	mldonkey
# config:	/etc/sysconfig/mldonkey

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

# Get network config
. /etc/sysconfig/network

# Check that networking is up.
if is_yes "${NETWORKING}"; then
	if [ ! -f /var/lock/subsys/network -a "$1" != stop -a "$1" != status ]; then
		msg_network_down mldonkey
		exit 1
	fi
else
	exit 0
fi

# Get service config
if [ -f /etc/sysconfig/mldonkey ]; then
	. /etc/sysconfig/mldonkey
fi

MLDONKEY_PATH=/usr/sbin/mlnetd
PROG=$(basename "$MLDONKEY_PATH")

getpids() {
	pgrep -u $USER $PROG
}

start() {
	if [ ! -f /var/lock/subsys/mldonkey ]; then
		msg_starting mldonkey

		daemon --fork --user $USER "cd ~$USER && exec $MLDONKEY_PATH > ${LOG:-/dev/null} 2>&1"
		RETVAL=$?

		# wait for it, it might die if config files are corrupted
		timeout=0
		while [ "$(getpids)" ]; do
			if [ $timeout -ge 5 ]; then
				break
			fi

			timeout=$((timeout + 1))
			sleep 1
		done

		if ! getpids > /dev/null; then
			nls "%s could not be started! Check logfile: %s" MLDonkey "$LOG"
			RETVAL=0
		fi

		# TEMP FIX, rc-scripts fails to keep nice level, when su is used
		# keep it, until rc-scripts is fixed.
		for pid in $(getpids); do
			renice ${SERVICE_RUN_NICE_LEVEL:-$DEFAULT_SERVICE_RUN_NICE_LEVEL} -p $pid > /dev/null
		done

		[ $RETVAL -eq 0 ] && touch /var/lock/subsys/mldonkey
	else
		msg_already_running mldonkey
	fi
}

stop() {
	if [ -f /var/lock/subsys/mldonkey ]; then
		# first nicely, via web interface
		BASE="http://"
		if [[ -n ${USERNAME} && -n ${PASSWORD} ]]; then
			BASE=${BASE}${USERNAME}:${PASSWORD}@
		fi

		msg_stopping mldonkey
		BASE=${BASE}${SERVER}:${PORT}
		wget -t 1 --spider ${BASE}/submit?q=close_fds -q
		wget -t 1 --spider ${BASE}/submit?q=save -q
		wget -t 1 --spider ${BASE}/submit?q=kill -q

		if [ "$(getpids)" ]; then
			fail
			show "Waiting for MLDonkey to stop"
			busy

			RETVAL=0
			timeout=0
			while [ "$(getpids)" ]; do
				if [ $timeout -ge 60 ]; then
					RETVAL=1
					break
				fi

				sleep 1
				timeout=$((timeout + 1))
			done
		fi

		# forcibly.
		# killproc() sais itself ok or fail, therefore the 'if' statement here
		if [ "$(getpids)" ]; then
			killproc $PROG
			RETVAL=$?
		else
			[ $RETVAL -eq 0 ] && ok || fail
		fi

		rm -f /var/lock/subsys/mldonkey >/dev/null 2>&1
	else
		msg_not_running mldonkey
	fi
}

RETVAL=0
case "$1" in
  start)
	start
	;;
  stop)
	stop
	;;
  restart|force-reload)
	stop
	start
	;;
  clean)
	stop && sleep 20
	rm ~mldonkey/.mldonkey/*.tmp >/dev/null 2>&1
	rm ~mldonkey/.mldonkey/mlnet.pid >/dev/null 2>&1
	;;
  status)
	status mldonkey $PROG
	exit $?
	;;
  *)
	msg_usage "$0 {start|stop|restart|force-reload|status|clean}"
	exit 3
esac

exit $RETVAL
