#!/bin/bash
#
# VERSION=9
# CHANGES="Updating lighttpd is now done by generalized script 'S35installpackages'."

# global variables #
export PATH="/bin:/sbin:/usr/bin:/usr/sbin:/usr/bin/X11:/usr/local/bin:/usr/local/sbin:/usr/fallback"
BEROCONF=/usr/fallback/beroconf

# functions #
function log {
	prefix="[init_lighttpd]"

	if [ -z "${2}" ]; then
		echo "${prefix} ${1}"
	else
		echo "${prefix} ${1}" >> ${2}
	fi
}

function fix_conf {

	HTTP_CONF=/etc/lighttpd.conf
	HTTP_INIT=/etc/init.d/S60httpd

	HTTP_CONF_CONT=$(cat ${HTTP_CONF})

	CHANGED=0

	# check if mod_fastcgi is still enabled
	grep "mod_fastcgi" ${HTTP_CONF} > /dev/null
	res0=${?}

	# check if certificate is mentioned in lighttpd.conf
	grep "/usr/conf/berofix.pem" ${HTTP_CONF} > /dev/null
	res1=${?}

	# remove dependency to mod_fastcgi, if it isn't available.
	if [ ! -f /usr/lib/mod_fastcgi.so ] && [ "${res0}" = "0" ]; then
		HTTP_CONF_CONT=$(echo "${HTTP_CONF_CONT/\"mod_fastcgi\", /}")
		CHANGED=1
	fi

	# is cert mentioned in conf?
	if [ "${res1}" = "0" ]; then
		# pem-file exists, just create symlink, otherwise remove section
		if [ -f /etc/lighttpd.pem ]; then
			ln -s /etc/lighttpd.pem /usr/conf/berofix.pem
		else
			HTTP_CONF_CONT=$(echo "${HTTP_CONF_CONT/\$SERVER\[\"socket\"\] == \":443\" \{*\}/}")
			HTTP_CONF_CONT=$(echo "${HTTP_CONF_CONT/\#VERSION=6/#VERSION=4}")
			CHANGED=1
		fi
	fi

	# if content of lighttpd.conf has changed, write it to disk.
	# remove the VERSION-file cause this is a non-version-change.
	if [ "${CHANGED}" = "1" ]; then
		mount -oremount,rw /
		echo "${HTTP_CONF_CONT}" > ${HTTP_CONF}
		sync; sleep 1; sync
		mount -oremount,ro /
	fi
}

# main #
case "${1}" in
	start)
		fix_conf
		log "Starting lighttpd."
		if [ ! -f /usr/conf/berofix.pem ]; then
			ln -s /etc/lighttpd.pem /usr/conf/berofix.pem
		fi

		lighttpd -f /etc/lighttpd.conf
		;;
	stop)
		log "Stopping lighttpd."
		killall lighttpd
		;;
	restart)
		${0} stop
		${0} start
		;;
	*)
		echo "Usage: ${0} {start|stop|restart}" >&2
		exit 1
		;;
esac
