#!/sbin/svc

MYLISTING="Web server for configuration interface."
CONTROL_GROUP="netconf"
MYCFG="/etc/lighttpd/lighttpd.conf"

# lighttpd requires the key and certificate in the same .PEM encoded file
KEYFILE="/etc/lighttpd/lighttpd.pem.local"
KEYVERSION="/etc/lighttpd/lighttpd.pem.version.local"
KEYVERSION_REQUIRED="1"

depend() {
	depends_on net_base
}

needs_new_key() {
	[ -e "${KEYFILE}" ] || return 0
	[ -e "${KEYVERSION}" ] || return 0
	CUR_VERSION="`cat "${KEYVERSION}"`"
	[ -n "${CUR_VERSION}" ] || return 0
	[ "${KEYVERSION_REQUIRED}" -le "${CUR_VERSION}" ] && return 1
	return 0
}

start() {
	if needs_new_key >& /dev/null
	then
		echo " * Generating a new self-signed SSL certificate for HTTPS"
		TMPFILE="`mktemp`"
		[ $? -eq 0 ] || return 1
		openssl req -new -x509 -days 3650 -nodes -batch \
			-keyout "${TMPFILE}" -out "${TMPFILE}"
		[ $? -eq 0 ] || return 1
		mv "${TMPFILE}" "${KEYFILE}"
		[ $? -eq 0 ] || return 1

		echo "${KEYVERSION_REQUIRED}" > "${KEYVERSION}"
	fi

	# do not self-daemonize, as no PID file support
	daemonize_orig /usr/sbin/lighttpd -D -f "${MYCFG}"
}

stop() {
        kill_pid
}
