#!/bin/sh /etc/rc.common
# Copyright (C) 2009 OpenWrt.org

NAME=sslh
PROG=/usr/sbin/sslh
START=95
PIDCOUNT=0

sslh_start()
{
	local section="$1"

	# check if section is enabled (default)
	local enabled
	config_get_bool enabled "${section}" enable 1
	[ "${enabled}" -eq 0 ] && return 1

	# increase pid file count to handle multiple instances correctly
	PIDCOUNT="$(( ${PIDCOUNT} + 1 ))"

	# prepare parameters (initialise with pid file)
	local args="-P /var/run/${NAME}.${PIDCOUNT}.pid"
	local val
	# A) listen parameter
	config_get val "${section}" listen
	[ ! -z "${val}" ] && append args "-p ${val}"
	# B) ssh parameter
	config_get val "${section}" ssh
	[ ! -z "${val}" ] && append args "-s ${val}"
	# C) ssl parameter
	config_get val "${section}" ssl
	[ ! -z "${val}" ] && append args "-l ${val}"
	# D) timeout (for ssh, then ssl is assumed)
	config_get val "${section}" timeout
	[ ! -z "${val}" ] && append args "-t ${val}"
	# E) verbose parameter
	local verbosed
	config_get_bool verbosed "${section}" verbose 0
	[ "${verbosed}" -ne 0 ] && append args "-v"

	# execute program and return its exit code
	[ "${verbosed}" -ne 0 ] && echo "${NAME}: section ${section} starting ${PROG} ${args}"
	${PROG} ${args}
	return $?
}

start()
{
	config_load "${NAME}"
	config_foreach sslh_start sslh
}

stop()
{
	local pidfile
	local rc=0

	# killing all known processes
	for pidfile in `ls /var/run/${NAME}.*.pid`
	 do
		start-stop-daemon -K -s KILL -p "${pidfile}" -n "${NAME}"
		[ $? -ne 0 ] && rc=1
		rm -f "${pidfile}"
	done

	# kill orphaned processes
	if [ ${rc} -ne 0 ]
	 then
		echo "${NAME}: inconsistency in pid files killing all orphaned processes"
		for pid in `pidof sslh`
		 do
			# check if correct program
			ps | grep "${pid}" | grep "${PROG}" >/dev/null
			[ $? -ne 0 ] && continue

			# kill process
			echo "Killing ${pid}..."
			kill -s KILL ${pid}
		done
	fi
}