#!/bin/sh
set -e

unconfigure_webservers()
{
	servers="apache apache2 apache-ssl apache-perl"
	for webserver in $servers; do
		if [ -e /etc/${webserver}/conf.d/mantis ]; then
			rm -f /etc/${webserver}/conf.d/mantis

			if [ -e /etc/init.d/${webserver} ]; then
				invoke-rc.d ${webserver} restart
			fi
		fi
	done
}

restore_oldconfig()
{
        if [ -f /etc/mantis/config.php ]
        then
                mv /etc/mantis/config.php /etc/mantis/config.php.dpkg-old
        fi
}

case "$1" in
	purge)
		unconfigure_webservers

		#prevent misconfigurations of permissions
		LIST_FILES_STATOVERRIDE="/etc/mantis/config_inc.php /etc/mantis/config_local.php /etc/mantis/custom_strings_inc.php /etc/mantis/config_db.php"
        	for i in $LIST_FILES_STATOVERRIDE
        	do
                	if [ dpkg-statoverride > /dev/null 2>&1 ]; then
				if dpkg-statoverride --list $i > /dev/null 2>&1; then
                        		dpkg-statoverride --remove $i
                       		fi
                	fi
        	done

		ucf --debconf-ok --purge /etc/mantis/config_db.php
		ucf --debconf-ok --purge /etc/mantis/config_inc.php

		if [ -d /etc/mantis ]; then
		    rm -rf /etc/mantis
		fi

		if [ -d /usr/share/mantis ]; then
		    rm -rf /usr/share/mantis
		fi
	;;

	remove)
		unconfigure_webservers
	;;

	abort-upgrade)
		restore_oldconfig
	;;

esac

#DEBHELPER#
