#!/bin/sh
#

PATH=/bin:/usr/bin:/sbin:/usr/sbin
DAEMON=/usr/sbin/hiawatha
PIDFILE=/var/run/hiawatha.pid
FLAGS="defaults 50"

NORMAL="\033[00;37m"
RED="\033[00;31m"
YELLOW="\033[00;33m"
GREEN="\033[00;32m"

test -f ${DAEMON} || exit 0

function start_hiawatha() {
	if [ -f ${PIDFILE} ]; then
		echo -e ${YELLOW}"Hiawatha is already running"${NORMAL}
	else
		echo -n "Starting webserver: "
		${DAEMON}
		echo -e ${GREEN}"Hiawatha"${NORMAL}
	fi
}

function stop_hiawatha() {
	if [ -f ${PIDFILE} ]; then
		echo -en "Stopping webserver: "${GREEN}
		PID=`cat ${PIDFILE}`
		kill -15 ${PID}

		WAIT="5"
		while [ -d /proc/${PID} ]; do
			if [ "$WAIT" != "0" ]; then
				sleep 1
				let WAIT=${WAIT}-1
			else
				echo -en ${RED}"warning, possible incorrect shutdown of "
				break
			fi
		done

		rm -f ${PIDFILE}
		echo -e "Hiawatha"${NORMAL}
	else 
		echo -e ${YELLOW}"Hiawatha is not running"${NORMAL}
	fi
}

case "$1" in
	start)
		start_hiawatha
		;;
	stop)
		stop_hiawatha
		;;
	restart)
		stop_hiawatha
		start_hiawatha
		;;
	reload)
		if [ -f ${PIDFILE} ]; then
			echo -n "Reloading configuration: "
			kill -USR1 `cat ${PIDFILE}`
			echo -e ${GREEN}"Hiawatha"${NORMAL}
		else 
			echo -e ${YELLOW}"Hiawatha is not running"${NORMAL}
		fi
		;;
	*)
		echo "Usage: $0 {start|stop|reload}"
		exit 1
		;;
esac

exit 0
