#!/bin/ksh
# vi:set ts=4 sw=4:
#
#ident "@(#)hcspm.ksh	1.8	05/14/98"
#
# Copyright (c) 1998 by Sun Microsystems, Inc.



PROGNAME="hcspm"

#fix send updated hcspm.conf file to Vickie when it is completed

#fix trap 'rm -f /tmp/$PROGNAME.$$.*; exit 1' 1 2 3 14 15

export PATH="/usr/bin:/usr/sbin:/usr/openwin/bin"

HOST="$(uname -n)"
ARCH="$(uname -p)"

CONFFILE="/etc/opt/SUNWisp/hc/hcspm.conf"

#! /usr/bin/ksh
# @(#)util.dot	1.3	05/11/98

CleanupAndExit() {
	# $1 == exit code

	/bin/rm -rf /tmp/$PROGNAME.$$.*
	exit $1
}

Usage() {
	# no args

	print "\n$(gettext 'Usage'): $PROGNAME $OPTS"
	CleanupAndExit 1
}

Error() {
	# $1 == msg body

	print "\n$(gettext 'Error'): $1"
	return 0
}

Warning() {
	# $1 == msg body

	print "\n$(gettext 'Warning'): $1"
	return 0
}

Fatal() {
	# $1 == msg body
	#
	# exits (with code 1)

	print "\n$(gettext 'Fatal'): $1"
	CleanupAndExit 1
}

CheckUidIsRoot() {
	case "$(/usr/xpg4/bin/id -ur)" in
		0) ;;
		*) Fatal "$(gettext 'must be run as') 'root' (UID=0)";;
	esac

	return 0
}

Post() {
	typeset VAR
	for VAR in "$@"; do
		eval print "$VAR = \'\$$VAR\'"
	done
	return 0
}


#
# InitLocale
# Initialize our locale.
#
InitLocale() {
	if [[ -z "$LC_ALL" && -z "$LC_MESSAGES" && -z "$LANG" ]] then
		return
	fi

	export TEXTDOMAIN=SUNWisp
	export TEXTDOMAINDIR=/opt/SUNWisp/lib/locale
}

ParseConfFile() {
	typeset LINE
	typeset ACTIVE
	typeset RESTART
	typeset METHOD
	typeset TYPE
	typeset FORMAT

	IFS=":"

	egrep -v '^$' $CONFFILE | egrep -v '^#' |
	while read LINE; do
		set $LINE

		ACTIVE="$1"
		RESTART="$2"
		METHOD="$3"
		FORMAT=$(gettext 'Restarting daemon with \"%s\"\n')

		if [[ -f "$ACTIVE" ]] then
			case "$METHOD" in
			process)
				if [[ -f $4 ]] then
					PID="$(<$4)"

					pstate=`ps -p $PID -o s | sed -n '2p'`
					if [[ $pstate = "" || `expr $pstate : [OSR]` = 0 ]] then
						logger -p daemon.err -t hcspm $(printf "$FORMAT" $RESTART)
						$RESTART
					fi
				else
					logger -p daemon.err -t hcspm $(printf "$FORMAT" $RESTART)
					$RESTART
				fi
				;;

			file)
				secs=$(hctouched $4)
				if [ $? = 0 -a $secs -gt $5 ]; then
					logger -p daemon.err -t hcspm $(printf "$FORMAT" $RESTART)
					$RESTART
				fi
				;;

			program)
				$4
				if [ $? -ne 0 ]; then
					logger -p daemon.err -t hcspm $(printf "$FORMAT" $RESTART)
					$RESTART 
				fi
				;;
			esac
		fi
	done

	return 0
}
# main

InitLocale

OPTSTRING="c:"
OPTS="[ -c configfile ]"

# process cmd line options
#
while getopts $OPTSTRING OPT; do
	case $OPT in
		c)	CONFFILE="$OPTARG";;
		\?)	Usage;;
	esac
done

shift $(expr $OPTIND - 1)

if [ $# -gt 0 ]; then
	fmtStr=$(gettext 'Too many args (remaining args = %s)\n')
	Fatal $(printf "$fmtStr" "$*")
fi

ParseConfFile

CleanupAndExit 0
