#! /bin/sh

. /etc/init.d/functions.sh
. /etc/conf.d/stunnel

description="SSL tunnel"
local DAEMON=/usr/sbin/stunnel
local BOA_PORT=$(sed -rne 's/^[[:space:]]*Port[[:space:]]+([[:digit:]]+).*/\1/p' \
		 /etc/httpd/conf/boa.conf)
conffile=/var/run/stunnel.conf

conditional_start_stunnel () {
	if [ "$STUNNEL_ENABLED" = yes ]; then
		rm -f $conffile
		cat <<-EOF >> $conffile
		pid = /var/run/stunnel/stunnel.pid
		cert = /etc/ssl/certs/server.pem
		setuid = stunnel
		setgid = crypto
EOF
		echo "debug = alert" >> $conffile
		echo "socket = a:IP_TOS=$STUNNEL_TOS" >> $conffile
		echo "socket = a:IPV6_TCLASS=$STUNNEL_TOS" >> $conffile
		echo "engine = auto" >> $conffile
		echo -e "\n[boa-https]" >> $conffile
		echo "	accept = :::$STUNNEL_PORT" >> $conffile
		echo "	connect = 127.6.6.6:$BOA_PORT" >> $conffile
		echo "	TIMEOUTclose = 0" >> $conffile
		start_daemon $DAEMON $conffile
	else
		information "disabled"
	fi
}

stop_stunnel() {
	stop_daemon $DAEMON
}

case "$1" in
	start)
		begin "Starting $description"
		conditional_start_stunnel
		end $?
		;;
	stop)
		begin "Stopping $description"
		stop_stunnel
		end $?
		;;
	restart)
		begin "Restarting $description"
		stop_stunnel && conditional_start_stunnel
		end $?
		;;
	*)
		error "Usage: $0 start|stop|restart"
		;;
esac

exit 0
