#!/bin/sh
set -e

avahi_install() {
	if [ -d /etc/avahi/services/ -a ! -e /etc/avahi/services/tt-rss.service -a ! -L /etc/avahi/services/tt-rss.service ] ; then
		ln -s ../../tt-rss/avahi.service /etc/avahi/services/tt-rss.service
	fi
}

lighttpd_install() {
	if which lighty-enable-mod >/dev/null 2>&1 ; then
		lighty-enable-mod tt-rss fastcgi
		avahi_install
	fi
}

apache2_install() {
	if [ -e /usr/share/apache2/apache2-maintscript-helper ] ; then
		. /usr/share/apache2/apache2-maintscript-helper
		apache2_invoke enconf tt-rss
		avahi_install
	fi
}

if [ "$1" = "configure" ]; then
		# tt-rss will write files into these directories
		chown -R www-data:www-data /var/lib/tt-rss
		chown -R www-data:www-data /var/cache/tt-rss

		# source debconf stuff
		if [ -f /usr/share/debconf/confmodule ]; then
			. /usr/share/debconf/confmodule
		fi

		# dbconfig-common
		if [ -f /usr/share/dbconfig-common/dpkg/postinst ]; then
			. /usr/share/dbconfig-common/dpkg/postinst
			dbc_generate_include="php:/etc/tt-rss/database.php"
			dbc_generate_include_owner="root:www-data"
			dbc_generate_include_perms="0640"

			if ! dbc_go tt-rss $@ ; then
				echo 'Automatic configuration using dbconfig-common failed!'
			fi
		fi

		# webserver configuration
		db_get tt-rss/reconfigure-webserver
		webservers="$RET"

		for webserver in $webservers; do
			webserver=${webserver%,}
			if [ "$webserver" = "lighttpd" ]; then
				lighttpd_install
			elif [ "$webserver" = "apache2" ]; then
				apache2_install
			fi

			# Reload webserver in any case, configuration might have changed
			# Redirection of 3 is needed because Debconf uses it and it might 
			# be inherited by webserver. See bug #446324.
			if [ -x /usr/sbin/invoke-rc.d ]; then
				invoke-rc.d $webserver reload 3>/dev/null || true
			else
				/etc/init.d/$webserver reload 3>/dev/null || true
			fi
		done
fi

#DEBHELPER#

exit 0
