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

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()
{
	start-stop-daemon --start --startas $DAEMON --quiet --pidfile $PIDFILE -- \
		--daemon $APMISER_OPTS
	# Return success iff daemon was successfully started
}

stop()
{
	start-stop-daemon --stop --signal HUP --quiet --pidfile $PIDFILE
	# Return success if daemon was indeed stopped
}

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 || true
	force_stop
	echo "."
	exit 0
	;;
try-restart)
	echo -n "Restarting automatic power miser daemon: apmiser"
	if stop ; then
		# The daemon was stopped
	 	force_stop
		start
		case "$?" in
			0) echo "." ; exit 0 ;;
			1) echo " (failed -- still running)." ; exit 1 ;;
			*) echo " (failed)." ; exit 1 ;;
		esac
	else
		echo " (not running)."
	 	force_stop
		exit 0
	fi
	;;
restart|force-reload)
	$0 stop
	$0 start
	exit
	;;
*)
	echo "Usage: /etc/init.d/apmiser {start|stop|restart|force-reload}" >&2
	exit 3
	;;
esac
