#!/bin/bash
#
# shibd Shibboleth Service Provider Daemon
#
# chkconfig: - 80 20
# description: Shibboleth 2 Service Provider Daemon
# processname: shibd
# pidfile: @-PKGRUNDIR-@/shibd.pid
# config: @-PKGSYSCONFDIR-@/shibboleth2.xml

### BEGIN INIT INFO
# Provides: shibd
# Required-Start: $local_fs $remote_fs $network
# Should-Start: $time
# Should-Stop: $time
# Required-Stop: $local_fs $remote_fs $network
# Default-Start: 3 5
# Default-Stop: 0 1 2 6 
# Short-Description: Shibboleth 2 Service Provider Daemon
# Description: Starts the separate daemon used by the Shibboleth Apache module to manage state and SAML interactions.
### END INIT INFO

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

shibd="@-PREFIX-@/sbin/shibd"
SHIBD_USER=root
SHIBD_UMASK=022
SHIBD_WAIT=30
prog=shibd
pidfile=@-PKGRUNDIR-@/shibd.pid
lockfile=/var/lock/subsys/$prog

[ -e /etc/sysconfig/$prog ] && . /etc/sysconfig/$prog

umask $SHIBD_UMASK

start() {
	echo -n $"Starting $prog: "
	if [ -f $lockfile ] ; then
		if [ -f $pidfile ]; then
			read kpid < $pidfile
			if checkpid $kpid 2>&1; then
				echo "process already running"
					return 1;
				else
					echo "lock file found but no process running for pid $kpid, continuing"
			fi
		fi
	fi

	# Make sure package run directory exists.
	[ -d @-PKGRUNDIR-@ ] || mkdir @-PKGRUNDIR-@

	export SHIBD_PID=$pidfile
	touch $pidfile
	chown $SHIBD_USER:$SHIBD_USER $pidfile

	# Handle transition from root to non-root packages.
	chown -R $SHIBD_USER:$SHIBD_USER @-PKGRUNDIR-@ @-PKGCACHEDIR-@ 2>/dev/null || :
	daemon --user $SHIBD_USER $shibd -p $pidfile -f -w $SHIBD_WAIT

	RETVAL=$?
	echo
		[ $RETVAL -eq 0 ] && touch $lockfile
	return $RETVAL
}

stop() {
	echo -n $"Stopping $prog: "
	killproc shibd

	RETVAL=$?
	echo
	[ $RETVAL -eq 0 ] && rm -f $lockfile $pidfile
	return $RETVAL
}

restart() {
	stop
	sleep 5
	start
}

reload() {
	restart
}

force_reload() {
	restart
}

rh_status() {
	# run checks to determine if the service is running or use generic status
	status $prog
}

rh_status_q() {
	rh_status >/dev/null 2>&1
}

case "$1" in
	start)
		rh_status_q && exit 0
		$1
		;;
	stop)
		rh_status_q || exit 0
		$1
		;;
	restart)
		$1
		;;
	reload)
		rh_status_q || exit 7
		$1
		;;
	force-reload)
		force_reload
		;;
	status)
		rh_status
		;;
	condrestart|try-restart)
		rh_status_q || exit 0
		restart
		;;
	*)
		echo $"Usage: $0 {start|stop|status|restart|condrestart|try-restart|reload|force-reload}"
		exit 2
esac

exit $?
