#!/bin/sh

# @(#)$Id: ipa.sh.template,v 1.3 2011/01/26 19:20:26 simon Exp $

#
# Shell script for ipa(8).  Available commands are:
#   start	start ipa if it is not running;
#   stop	stop ipa if it is running;
#   restart	stop and start ipa (the same checks);
#   reload	reload configuration file;
#   status	check if ipa is running;
#   kill	terminate ipa.

ipa=/usr/pkg/bin/ipa		# Path to ipa.
pid_file=/var/run/ipa.pid	# Path to PID-file.
workdir=/			# Working directory.
ipa_args=			# Global arguments.
ipa_start_args=${ipa_args}	# Arguments for running ipa.
ipa_sig_args=${ipa_args}	# Arguments for "ipa -k ...".
stop_wait_count=10		# How many times to check PID-file.
stop_wait_sleep=1		# Seconds to sleep between PID-file checks.

if [ ! -f ${ipa} ]; then
	echo "$0: Error: cannot find ${ipa}."
	exit 1
fi

if [ ! -x ${ipa} ]; then
	echo "$0: Error: ${ipa} is not executable."
	exit 1
fi

ipa_start()
{
	${ipa} ${ipa_start_args} && echo -n " ipa"
}

ipa_stop()
{
	${ipa} ${ipa_sig_args} -k shutdown || exit 1
	i=0
	while [ -f ${pid_file} ]; do
		i=`expr ${i} + 1`
		sleep ${stop_wait_sleep}
		if [ ${i} -eq ${stop_wait_count} ]; then
			echo "$0: ${pid_file} is still present!"
			return 1
		fi
	done
	return 0
}

cd ${workdir}

case "$1" in
start)
	ipa_start
	;;
stop)
	ipa_stop
	;;
restart)
	ipa_stop
	ipa_start
	;;
reload)
	${ipa} ${ipa_sig_args} -k reconfigure
	;;
status)
	${ipa} ${ipa_sig_args} -k test
	;;
kill)
	${ipa} ${ipa_sig_args} -k kill
	;;
*)
	echo "$0: Usage: $0 start|stop|restart|reload|status|kill"
	exit 1
	;;
esac
