#!/bin/sh
umask 022

prefix=/usr
piddir=/var/run
config=/etc/thttpd.conf

THTTPD=$prefix/sbin/thttpd
PIDFILE=$piddir/thttpd.pid

stop_service() {
    if [  -r $PIDFILE  -a  ! -z ${PIDFILE}  ]; then
	    PID=`cat ${PIDFILE}`
    fi
    if [  ${PID:=0} -gt 1 -a  ! "X$PID" = "X "  ]; then
	    kill ${PID}
    else
	    echo "Unable to read PID file"
    fi
}

start_service() {

    if [ -z "$(grep thttpd /etc/passwd 2>/dev/null)" ]; then
        echo "$0: Creating system user 'thttpd' with generic settings.  Review and modify as required."
        yes '' | adduser thttpd >/dev/null 2>&1 || yes '' | useradd thttpd >/dev/null 2>&1
    fi

    mkdir -p $piddir

    # Start thttpd
    printf "Starting $THTTPD: "         ; $THTTPD -C $config

    thhtpd_rc=$?
    if [ $thhtpd_rc -ne 0 ]; then
            echo "[FAIL]"
	    echo "$0: Error ${thttpd_rc} starting ${THTTPD}... bailing."
	    exit $thttpd_rc
    fi
    echo "[ OK ]"
}

case $1 in

'start')
    start_service
    ;;

'stop')
    stop_service
    ;;

'restart')
    stop_service
    start_service
    ;;

*)
    echo "Usage: $0 [start|stop|restart]"
    ;;
esac
