#!/bin/sh
#
# chkconfig: 2345 51 89
# description: The UPS drivers
# config: /etc/ups/

WITHOUT_RC_COMPAT=1

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

# Source service configuration.
SourceIfNotEmpty /etc/sysconfig/upsd

LOCKFILE=/var/lock/subsys/upsdrv
RETVAL=0
DRVLIST=

get_drvlist()
{
	DRVLIST="$((find $CHROOTDIR/ -maxdepth 1 -name '*-*.pid' -type f |
			sed -ne 's,'$CHROOTDIR'/\([^/-]\+\)-[^/-]\+\.pid$,/lib/nut/\1,p';
		    upsdrvctl list 2>/dev/null |grep ^/
		   ) |sort -u)"
}

upsd_configured()
{
	egrep -qs '^[[:space:]]*[^#[:space:]]' "$UPS_CONF" || return
	cp -p "$UPS_CONF" "$CHROOTDIR$UPS_CONF"
}


start()
{
	upsd_configured || return 0

	action "Starting UPS drivers:" upsdrvctl $UPSDRV_OPTIONS start
	RETVAL=$?
	[ $RETVAL -eq 0 ] && touch "$LOCKFILE"
	return $RETVAL
}

stop()
{
	local f list rc=0
	get_drvlist
	[ -n "$DRVLIST" ] || rc=3
	for f in $DRVLIST; do
		msg_stopping $"${f##*/} UPS driver"
		stop_daemon --expect-user upsdrv --no-announce -- "$f"
		RETVAL=$?
		[ "$RETVAL" = 0 ] || rc="$RETVAL"
	done
	RETVAL="$rc"
	[ $RETVAL -eq 0 ] && rm -f "$LOCKFILE"
	return $RETVAL
}

restart()
{
	stop
	start
}

statuses()
{
	local f list rc=0
	get_drvlist
	[ -n "$DRVLIST" ] || rc=3
	for f in $DRVLIST; do
		status --expect-user upsdrv -- "$f"
		RETVAL=$?
		[ "$RETVAL" = 0 ] || rc="$RETVAL"
	done
	RETVAL="$rc"
	return $RETVAL
}

# See how we are called.
case "$1" in
	start)
		start
		;;
	stop)
		stop
		;;
	status)
		statuses
		;;
	restart|reload)
		restart
		;;
	condstart)
		if [ ! -e "$LOCKFILE" ]; then
			start
		fi
		;;
	condstop)
	  	if [ -e "$LOCKFILE" ]; then
			stop
		fi
		;;
	condrestart|condreload)
		if [ -e "$LOCKFILE" ]; then
			restart
		fi
		;;
	*)
		msg_usage "${0##*/} {start|stop|status|restart|condstart|condstop|condrestart}"
		RETVAL=1
esac

exit $RETVAL
