#!/bin/sh
#
# Start or stop the apmiser daemon
#
# This script is part of the tpctl package
#
# Aug 2003: Written by Thomas Hood

set +e   # Don't exit on error

PATH=/bin:/usr/bin:/sbin:/usr/sbin

APMISER_OPTS=""
[ -f /etc/default/apmiser ] && . /etc/default/apmiser

DAEMON=/usr/sbin/apmiser
PIDFILE=/var/run/apmiser.pid

test -s $DAEMON || exit 0

start()
{
	# Return success if daemon was successfully started
	start-stop-daemon --start --startas $DAEMON --quiet --pidfile $PIDFILE -- --daemon $APMISER_OPTS
}

stop()
{
	# Return success if daemon was indeed stopped
	start-stop-daemon --stop --retry=HUP/3/KILL/3 --quiet --pidfile $PIDFILE
}

force_stop()
{
	PIDOF_APMISER="$(pidof -x -o "$$" -o "$PPID" apmiser)"
	[ "$PIDOF_APMISER" ] && kill "$PIDOF_APMISER" 2>/dev/null || true
	rm -f $PIDFILE
	return 0
}

case "$1" in
start)
	echo -n "Starting automatic power miser daemon: apmiser"
	start
	case "$?" in
		0) echo "." ; exit 0 ;;
		1) echo " (already running)." ; exit 0 ;;
		*) echo " (failed)." ; exit 1 ;;
	esac
	;;
stop)
	echo -n "Stopping automatic power miser daemon: apmiser"
	stop
	force_stop
	echo "."
	exit 0
	;;
try-restart)
	echo -n "Restarting automatic power miser daemon: apmiser"
	stop
	case "$?" in
		0)
			# The daemon has been stopped
		 	force_stop
			start
			case "$?" in
				0) echo "." ; exit 0 ;;
				1) echo " (failed -- old process is still running)." ; exit 1 ;;
				*) echo " (failed to start)." ; exit 1 ;;
			esac
			;;
		1)
			echo " (not running)."
		 	force_stop
			exit 0
			;;
		2)
			echo -n " (failed to stop). Forcibly stopping apmiser"
		 	force_stop
		 	echo "."
			exit 1
			;;
	esac
	;;
restart|force-reload)
	$0 stop && $0 start
	exit
	;;
*)
	echo "Usage: /etc/init.d/apmiser {start|stop|restart|force-reload}" >&2
	exit 3
	;;
esac
