#!/bin/sh

set -e

#DEBHELPER#

reload_apache()
{
    if apache2ctl configtest 2>/dev/null; then
	if [ -x /usr/sbin/invoke-rc.d ]; then
            invoke-rc.d apache2 $1 3>/dev/null || true
	else
            /etc/init.d/apache2 $1 3>/dev/null || true
	fi
    else
        echo "Your Apache 2 configuration is broken, so we're not restarting it for you."
    fi
}


case "$1" in
    configure)
	CONF="owncloud"
	COMMON_STATE=$(dpkg-query -f '${Status}' -W 'apache2.2-common' 2>/dev/null | awk '{print $3}' || true)
	if [ -e /usr/share/apache2/apache2-maintscript-helper ] ; then
		. /usr/share/apache2/apache2-maintscript-helper
		apache2_invoke enmod rewrite
		if [ -e /etc/apache2/conf-available/$CONF.conf ] ; then
			apache2_invoke enconf $CONF || exit $?
		fi
	elif [ "$COMMON_STATE" = "installed" ] || [ "$COMMON_STATE" = "unpacked" ] ; then
		if [ -d /etc/apache2/conf.d/ ] && [ ! -L /etc/apache2/conf.d/$CONF.conf ] ; then
			ln -s ../conf-available/$CONF.conf /etc/apache2/conf.d/$CONF.conf
		fi
		# Test whether a2enmod is available (and thus also apache2ctl).
		if [ -x /usr/sbin/a2enmod ]; then
			# Enable the Apache2 rewrite module if not already enabled
			a2enmod rewrite > /dev/null || true
			# Restart Apache to really enable the module and load
			# /etc/apache2/conf.d/owncloud.conf.
			reload_apache restart
		fi
	fi
	# Create empty logfile if needed
	file=/var/log/owncloud.log
	if [ ! -f $file ]; then
		touch $file
		chown www-data:adm $file
		chmod 0640 $file
	fi
	# Update the database on upgrade
	# Don’t let it fail, since it exits with 3 if no upgrade is necessary
	if [ -e /etc/owncloud/config.php ] ; then
		su -s /bin/sh -c "/usr/sbin/occ upgrade" www-data || true
	fi
    ;;

    abort-upgrade|abort-remove|abort-deconfigure)
    ;;

    *)
        echo "postinst called with unknown argument \`$1'" >&2
        exit 1
    ;;
esac

exit 0
