#!/bin/sh

### BEGIN INIT INFO
# Provides:		hippotatd
# Required-Start:	$network $local_fs
# Required-Stop:	$network $local_fs
# Should-Start:		userv $syslog
# Should-Stop:		userv $syslog
# Default-Start:	2 3 4 5
# Default-Stop:		0 1 6
# Short-Description:	hippotatd
# Description:          Asinine IP over HTTP server
### END INIT INFO

DAEMON=/usr/sbin/hippotatd
MAIN_CONFIG=/etc/hippotat/main.cfg
USER=_hippotat
GROUP=_hippotat
PIDFILE=/var/run/hippotat/hippotatd.pid
LOGFACILITY=daemon
CHECK_FIREWALL=true
# HIPPOTATD_ARGS
AS_USER=as_user_userv
DESCRIPTION='Asinine IP over HTTP server'
if type authbind >/dev/null 2>&1; then AUTHBIND=authbind; fi

test -e /etc/default/hippotatd && . /etc/default/hippotatd

set -e

test -f $DAEMON || exit 0
egrep '^[^ 	#]' $MAIN_CONFIG >/dev/null 2>&1 || exit 0

. /lib/lsb/init-functions

as_user_userv () {
	userv --override '
		execute-from-path
		no-suppress-args
	' $USER "$@"
}

ssd () {
	set +e
	start-stop-daemon --quiet --user $USER --pidfile=$PIDFILE "$@"
	rc=$?
	set -e
}
ensure_dirs () {
	pidfiledir=${PIDFILE%/*}
	if test -d ${pidfiledir}; then return; fi
	mkdir -m 755 $pidfiledir
	chown $USER $pidfiledir
}

dump_firewall () {
	iptables -L -v -n
}

print_config () {
	$AS_USER $DAEMON $HIPPOTATD_ARGS --print-config "$1"
}

check_firewall () {
	$CHECK_FIREWALL || return 0
	vnetwork=$(print_config vnetwork)
	if dump_firewall | fgrep " $vnetwork " >/dev/null; then :; else
		log_failure_msg \
 "error: no entry in firewall for insecure vnetwork $vnetwork"
		exit 1
	fi
}

do_start () {
	check_firewall
	ensure_dirs
	ssd	--chuid $USER --start 				\
		--startas /bin/sh -- -ec '"$@"' x		\
		$AUTHBIND $DAEMON --daemon --pidfile=$PIDFILE	\
		--syslog-facility=$LOGFACILITY $HIPPOTATD_ARGS
}
do_stop () {
	ssd	--stop --oknodo --retry 5
}

case "$1" in
start)
	log_daemon_msg "Starting $DESCRIPTION" hippotatd
	do_start
	log_end_msg $rc
	exit $rc
	;;

stop)
	log_daemon_msg "Stopping $DESCRIPTION" hippotatd
	do_stop
	log_end_msg $rc
	exit $rc
	;;

restart|force-reload)
	log_daemon_msg "Restarting $DESCRIPTION" hippotatd
	do_stop
	sleep 1
	do_start
	log_end_msg $rc
	;;

reload)
	log_failure_msg "Cannot reload hippotat - need restart"
	exit 1
	;;

*)
	echo >&2 "$0: unknown action $1"
	exit 1
	;;

esac

exit 0
