#!/bin/sh
#
# Post removal script for Tomcat
#

set -e

#DEBHELPER#

CONFFILES="tomcat-users.xml web.xml server.xml logging.properties context.xml catalina.properties jaspic-providers.xml"

case "$1" in
    remove)
        # Remove the ROOT webapp if not modified
        RWLOC="/var/lib/tomcat10/webapps/ROOT"
        RWFILES="$RWLOC/index.html $RWLOC/META-INF/context.xml"
        if [ "`(cat $RWFILES | md5sum -) 2>/dev/null | cut -d ' ' -f 1`" \
                            = "@ROOT_WEBAPP_MD5SUM@" ] ; then
            rm $RWFILES
            rmdir --ignore-fail-on-non-empty \
                /var/lib/tomcat10/webapps/ROOT/META-INF \
                /var/lib/tomcat10/webapps/ROOT \
                /var/lib/tomcat10/webapps \
                /var/lib/tomcat10 || true
        fi

        # Remove CATALINA_BASE/lib if not empty
        if [ -d /var/lib/tomcat10/lib ] && [ -z "`(find /var/lib/tomcat10/lib/classes -type f)`" ] ; then
            rmdir --ignore-fail-on-non-empty \
                /var/lib/tomcat10/lib/classes \
                /var/lib/tomcat10/lib || true
        fi

        # Remove the cache files (compiled JSP files)
        if [ -d "/var/cache/tomcat10" ] ; then
            rm -rf /var/cache/tomcat10
        fi

        # Remove the auto-generated catalina.policy file
        if [ -d "/var/lib/tomcat10/policy" ] ; then
            rm -rf /var/lib/tomcat10/policy
        fi
    ;;

    purge)
        # Ignore errors during purge
        set +e

        # Remove the configuration files
        rm -rf /etc/logrotate.d/tomcat10
        rm -rf /etc/default/tomcat10
        for conffile in $CONFFILES;
        do
            rm -f /etc/tomcat10/$conffile
        done

        # Unregister the configuration files from ucf
        if which ucf >/dev/null; then
            ucf --purge /etc/logrotate.d/tomcat10
            ucf --purge /etc/default/tomcat10
            for conffile in $CONFFILES;
            do
                ucf --purge /etc/tomcat10/$conffile
            done
        fi

        # Remove the log files
        rm -rf /var/log/tomcat10

        # Remove the temp directory
        rm -rf /var/lib/tomcat10/temp

        # Remove the CATALINA_BASE directory if empty
        if [ -d "/var/lib/tomcat10" ] ; then
            rmdir --ignore-fail-on-non-empty /var/lib/tomcat10
        fi

        # Remove the configuration directories
        rmdir --ignore-fail-on-non-empty /etc/tomcat10/policy.d /etc/tomcat10/Catalina/* /etc/tomcat10/Catalina /etc/tomcat10

        set -e
    ;;

    upgrade|failed-upgrade|abort-install|abort-upgrade|disappear)
        # Nothing to do here
    ;;

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