#!/bin/sh
#
# Dummy upsd keyboard interface
#
# version 1.04 5-16-98 Michael A. Robinton
#
# You may wish to start the upsd daemon normally 
# and just use this utility to push it data

# Set the port number to use here
PORT=2043

# Source of the data in the real world
#SOURCE="-s 192.168.1.164"
SOURCE=/dev/cua1

DAEMON=/sbin/upsd

# ----- no user options beyond this point ------
if [ ! -z $PORT ]; then
    PORT=" -p ${PORT}"
fi
OPTIONS="$PORT $SOURCE"
COMMAND=${DAEMON}${OPTIONS}

# 
# It's your job to make sure any
# unwanted copies of 'upsd' are
# not running, but try to help by
# identifying running upsd's
#
getupsdpid () {
    UPSDPID=`ps ax | grep $DAEMON`
    UPSDPID=`echo $UPSDPID | grep -E ":[0-9][0-9] $DAEMON" | cut -f1 -d\ `
}

# if a upsd daemon is running, kill it
killifpresent () {
    getupsdpid
    if [ ! -z $UPSDPID ]; then
	ps $UPSDPID
	echo "        was killed"
	kill -9 $UPSDPID
    fi
}

# clean up and exit
cleanexit () {
    if [ -e /tmp/upsds ]; then
	rm /tmp/upsds
    fi
    exit 0
}

# ----------- MAIN program --------------

if [ -e /tmp/upsds ]; then
    rm /tmp/upsds		# clean entry
fi

getupsdpid
if [ ! -z $UPSDPID ]; then
    echo -e "\n         WARNING"
    ps $UPSDPID
    echo -e " is running, type 'kill' to terminate\n"
fi

echo -e "\nType 'help' for instructions\n"

# get the user input
while [ 1 ]; do
    echo -n 'status= '
    read RESPONSE

    case $RESPONSE in

	'' )				# null
	    ;;

	q* )				# just quit
	    cleanexit
	    ;;

	e* | x* )			# exit
	    killifpresent
	    cleanexit
	    ;;

	k* )				# kill upsd daemon
	    killifpresent
	    if [ -z $UPSDPID ]; then
		echo 'no upsd daemon is running'
	    fi
	    ;;

	m* )				# start a master daemon
	    killifpresent
	    $COMMAND -d master
	    ;;

	l* )				# start a local daemon
	    killifpresent
	    $COMMAND -d local
	    ;;

	0 | 1 | 2 | 3 | '?' )		# good input
	    echo $RESPONSE > /tmp/upsds
	    ;;

	* )		# print this help
	    echo '

       NOTE: only the FIRST character of each legal string is required
Legal input:

	quit	to quit

	exit	or
	 xit	to  kill any running upsd daemon and quit

	kill	kill any running upsd daemon

	master	set master mode, kill and start upsd daemon
	local	set local mode, kill and start upsd daemon

	0	for Power OK
	1	for Power Fail, On Battery
	2	for Low Battery
	3	for Cable Fail
	?	for Status Unknown
		this will also occur for real in
		master mode if the daemon is unloaded
'
	    ;;
    esac
done
