#!/bin/bash
#
# Hiawatha start/stop script for Linux
#
### BEGIN INIT INFO
# Provides:          hiawatha httpd httpd-cgi
# Required-Start:    $syslog $network $remote_fs
# Required-Stop:     $syslog $network $remote_fs
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: Hiawatha webserver
# Description:       Hiawatha, a secure and advanced webserver.
### END INIT INFO

PATH="/bin:/usr/bin:/sbin:/usr/sbin"
HIAWATHA="/usr/sbin/hiawatha"
WIGWAM="/usr/sbin/wigwam"
PIDFILE="/var/run/hiawatha.pid"

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

if [ ! -f ${HIAWATHA} ]; then
	echo -e "${HIAWATHA} not found."
	exit 5
fi

function start_hiawatha {
	if [ -f ${PIDFILE} ]; then
		echo -e "${YELLOW}Hiawatha is already running${NORMAL}"
	else
		${WIGWAM} -q
		result=$?

		if [ "${result}" = "0" ]; then
			echo -n "Starting webserver: "
			${HIAWATHA}
			result=$?
			if [ "${result}" = "0" ]; then
				echo -e "${GREEN}Hiawatha${NORMAL}"
			else
				echo -e "${RED}error!${NORMAL}"
			fi
		else
			echo -e "${RED}Hiawatha has NOT been started!${NORMAL}"
		fi
	fi
}

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

		WAIT="10"
		while [ -d /proc/${PID} ]; do
			if [ "${WAIT}" != "0" ]; then
				sleep 1
				let WAIT=${WAIT}-1
			else
				kill -9 ${PID}
				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}"
		exit 7
	fi
}

function config_check {
	echo -e "${YELLOW}Configuration check via Wigwam...${NORMAL}"
	${WIGWAM}
	echo
	echo -e "${YELLOW}Configuration check via Hiawatha...${NORMAL}"
	${HIAWATHA} -k
}

function show_status {
	if [ ! -f $PIDFILE ]; then
		echo -e "${RED}Hiawatha is not running${NORMAL}"
		exit 3
	elif ps `cat $PIDFILE` >/dev/null 2>&1; then
		echo -e "${GREEN}Hiawatha is running${NORMAL}"
	else
		echo -e "${RED}Hiawatha is not running but PID file exists${NORMAL}"
		return 1
	fi
}

case "$1" in
	start)
		start_hiawatha
		;;
	stop)
		stop_hiawatha
		;;
	restart|force-reload)
		stop_hiawatha
		start_hiawatha
		;;
	check)
		config_check
		;;
	status)
		show_status
		;;
	*)
		echo "Usage: $0 {start|stop|restart|force-reload|check|status}"
		if [ "$1" = "reload" ]; then
			exit 3
		fi
		exit 1
		;;
esac

exit 0
