#!/bin/bash
#
# VERSION=11
# CHANGES="add exporting openssl.cnf file"

# 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

export OPENSSL_CONF=/usr/local/ssl/openssl.cnf

# 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 does not exist, we remove the section
		if [ ! -f /etc/lighttpd.pem ]; then
			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
}

function check_pem {

	HTTP_PEM=/usr/conf/berofix.pem
	HTTP_PEM_BACKUP=/etc/lighttpd.pem

	openssl x509 -in ${HTTP_PEM} -noout -text &> /dev/null	
	res0=${?}

	openssl rsa -in ${HTTP_PEM} -check &>/dev/null 
	res1=${?}
	if [[ ! "${res0}" = "0" ]] && [[ ! "${res1}" = "1" ]]; then
		echo "1" > /tmp/error_certificate.log
		rm -f ${HTTP_PEM}
	fi

	cert=$(openssl x509 -noout -modulus -in ${HTTP_PEM} | openssl md5)
	privkey=$(openssl rsa -noout -modulus -in ${HTTP_PEM} | openssl md5)
	if [ ! "${cert}" = "${privkey}" ];
	then
		echo "1" > /tmp/error_certificate.log
		rm -f ${HTTP_PEM}
	fi

	if [ ! -f ${HTTP_PEM} ]; then
		ln -s ${HTTP_PEM_BACKUP} ${HTTP_PEM} &> /dev/null
	fi
}

# main #
case ${1} in
	start)
		fix_conf
		check_pem
		log "Starting lighttpd."
		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
