#!/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
		apache2_invoke enconf $CONF
	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
        # Fix ownership and permissions of existing configuration.
        if [ -f /etc/owncloud/config.php ]; then
            chown www-data:www-data /etc/owncloud/config.php
            chmod 0640 /etc/owncloud/config.php
        fi
        if [ -f /etc/owncloud/htaccess ]; then
            chown www-data:www-data /etc/owncloud/htaccess
            chmod 0640 /etc/owncloud/htaccess
        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
	# Replace directory with symlink [ Can be removed before Jessie ]
	subdir="/usr/share/owncloud/3rdparty/"
	for dir in ${subdir}css/chosen ${subdir}js/chosen; do
		if [ -d $dir ] && [ ! -L $dir ]; then
			if rmdir $dir 2>/dev/null; then
				ln -sf ../../../javascript/chosen $dir
			fi
		fi
	done
	dir="/usr/share/owncloud/3rdparty/fontawesome"
	if [ -d $dir ] && [ ! -L $dir ]; then
		if rmdir $dir 2>/dev/null; then
			ln -sf ../../fonts-font-awesome $dir
		fi
	fi
	dir="/usr/share/owncloud/3rdparty/Jcrop"
	if [ -d $dir ] && [ ! -L $dir ]; then
		if rmdir $dir 2>/dev/null; then
			ln -sf ../../javascript/jcrop $dir
		fi
	fi

    ;;

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

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

exit 0
