#!/sbin/runscript
# Copyright 1999-2006 Gentoo Foundation
# Distributed under the terms of the GNU General Public License v2

BTPDUSERHOME=`getent passwd ${BTPDUSER} | cut -d : -f 6`
BTPDHOME=${BTPDUSERHOME}/.btpd
BTPDSTARTUPLOG=${BTPDHOME}/startup.log
	
depend() {
	need net
}

checkconfig() {
	if [ -z ${BTPDUSER} ]; then

		eerror "Must edit /etc/conf.d/btpd first."
		return 1

	elif [ -z "`getent passwd ${BTPDUSER}`" ]; then

		eerror "Check /etc/conf.d/btpd's \${BTPDUSER}. '${BTPDUSER}' doesn't exist."
		return 1
	fi
}

start() {

	ebegin "Starting BitTorrent Protocol Daemon"
	checkconfig || return 1

	if pgrep -u ${BTPDUSER} btpd >/dev/null; then
                eerror "An instance of btpd is already running"
                return 1
        else
		su ${BTPDUSER} -c "btpd ${BTPDEXTRARGS}"

		sleep 2

		if ! pgrep -u ${BTPDUSER} btpd > /dev/null; then
		eerror "BitTorrent Protocol Daemon couldn't be started ! Check logfile: ${BTPDSTARTUPLOG}"
		return 1
		fi
	fi

	eend $?
}

stop() {
	checkconfig || return 1

	local retries=0

	ebegin "Stopping BitTorrent Protocol Daemon"
	while [ -n "`pgrep -u ${BTPDUSER} btpd`" ] && [ ${retries} -lt 4 ]; do
		if test ${retries} -eq 0; then
			su ${BTPDUSER} -c "btcli kill"
		else
			kill -9 "`pgrep -u ${BTPDUSER} btpd`"
		fi

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

	if [ ${retries} -lt 4 ]; then
		return 0
	else
		eerror "Unable to stop btpd"
		return 1
	fi

	eend $?
}

restart() {
	svc_stop
	sleep 3
	svc_start
}
