#!/bin/sh -
PATH="/usr/ucb:/usr/bsd:/bin:/usr/bin:$PATH:/usr/local/etc/httpd"

######################### Custom Configuration ################################

HTTPD_HOST=somehost.cs.indiana.edu		# Server host

httpd="${HTTPD_DIR-$HOME/httpd}"		# Httpd installation dir
pidfile="${HTTPD_PID-$httpd/logs/httpd.pid}"	# Pid file
nohttpd="${HTTPD_WNH-$httpd/logs/.nohttpd}"	# Start suppression file
NOHTTPD="${HTTPD_QNH-$httpd/logs/.NOHTTPD}"	# Silent start suppression file

# Environment for httpd to run under
path="$httpd/bin:$httpd"\
":$HOME/bin:/usr/local/bin:/usr/ucb:/usr/bsd:/bin:/usr/bin"
umask=022

# Base httpd invocation command, run under httpd environment PATH
basecmd="httpd -d $httpd"

rsig=-HUP	# Restart signal
ksig=-TERM	# Kill signal
sleep=1		# Seconds to wait after sending a signal

####################### End Custom Configuration ##############################

# starthttpd - start, restart or kill an HTTP daemon, as needed
# Steve Kinzler, steve@kinzler.com, Sep 94
# https://kinzler.com/me/home.html#webadm

arg=; force=; bad=

while :
do
	case $# in
	0)	break;;
	*)	case "$1" in
		-[rkK])	arg="$1";;
		-f)	force="$1";;

		--)	shift; break;;
		-h)	bad=t; break;;
		-?*)	bad=t; echo "$0: unknown option ($1)" 1>&2;;
		*)	bad=t; break;;
		esac
		shift;;
	esac
done

case "$bad" in
?*)	cat << EOF 1>&2
usage: $0 [ -r | -k | -K ] [ -f ]
       [ -- extra httpd arguments ]
	-r	restart (kill $rsig) an existing daemon or start a new one
	-k	kill (kill $ksig) any existing daemon
	-K	kill (kill $ksig) any existing daemon then start a new one
	-f	force action, even if on the wrong server host
Without an option, the only action taken is to start a new daemon if
one isn't already running.  If either $nohttpd
or $NOHTTPD exists, then no new servers are started,
printing a warning message if the first file exists.
EOF
	exit 1;;
esac

case "$force,$HTTPD_HOST" in
,?*)	host=${HOST-${HOSTNAME-`(hostname) 2> /dev/null`}}
	case "$host" in
	'')	host=`uname -n`;;
	esac
	host=`	    echo "$host"       | sed 's/\..*//' | tr '[A-Z]' '[a-z]'`
	HTTPD_HOST=`echo "$HTTPD_HOST" | sed 's/\..*//' | tr '[A-Z]' '[a-z]'`
	case "$host" in
	"$HTTPD_HOST")	;;
	'')	echo "$0: cannot determine hostname" 1>&2; exit 2;;
	*)	echo "$0: wrong server host ($host != $HTTPD_HOST)" 1>&2
		exit 3;;
	esac;;
esac

pid=`cat "$pidfile" 2> /dev/null`

case "$arg" in
-k|-K)	case "$pid" in
	?*)	kill $ksig "$pid"; sleep "$sleep";;
	esac
	case "$arg" in
	-k)	exit 0;;
	esac;;

*)	case "$pid" in
	?*)	case "`kill -CONT "$pid" 2>&1`" in
		'')	case "$arg" in
			-r)	kill $rsig "$pid"; sleep "$sleep";;
			esac
			exit 0;;
		esac;;
	esac;;
esac

if test -f "$nohttpd"
then
	echo "$0: not starting httpd ($nohttpd exists)" 1>&2; exit 0
fi
test -f "$NOHTTPD" && exit 0

PATH="$path"; export PATH
umask $umask

exec $basecmd ${1+"$@"}
