#!/bin/sh
# postrm script for campcaster
#
# see: dh_installdeb(1)

set -e

# summary of how this script can be called:
#        * <postrm> `remove'
#        * <postrm> `purge'
#        * <old-postrm> `upgrade' <new-version>
#        * <new-postrm> `failed-upgrade' <old-version>
#        * <new-postrm> `abort-install'
#        * <new-postrm> `abort-install' <old-version>
#        * <new-postrm> `abort-upgrade' <old-version>
#        * <disappearer's-postrm> `disappear' <overwriter>
#          <overwriter-version>
# for details, see http://www.debian.org/doc/debian-policy/ or
# the debian-policy package

vardir=/var/lib/campcaster


if [ -d /etc/postgresql/8.1 ]; then
    postgresql_init_script=/etc/init.d/postgresql-8.1
elif [ -d /etc/postgresql/8.2 ]; then
    postgresql_init_script=/etc/init.d/postgresql-8.2
elif [ -d /etc/postgresql/8.3 ]; then
    postgresql_init_script=/etc/init.d/postgresql-8.3
elif [ -d /etc/postgresql/8.4 ]; then
    postgresql_init_script=/etc/init.d/postgresql-8.4
else
    echo "no postgresql 8.1, 8.2, 8.3 or 8.4 found" >&2
    exit 1
fi
postgres_user=postgres

ls_database=Campcaster
ls_dbuser=campcaster


#-------------------------------------------------------------------------------
#  Function to check for the existence of an executable on the PATH
#
#  @param $1 the name of the exectuable
#  @return 0 if the executable exists on the PATH, non-0 otherwise
#-------------------------------------------------------------------------------
check_exe() {
    if [ -x "`which $1 2> /dev/null`" ]; then
        return 0;
    else
        return 1;
    fi
}


case "$1" in
    remove|upgrade|failed-upgrade|abort-install|abort-upgrade)
    ;;

    purge|disappear)
        # check for the required tools
        check_exe "psql" || psql_found=no

        if [ "x$psql_found" != "xno" ] ; then
            # kill open connections to the Campcaster database
            $postgresql_init_script stop
            $postgresql_init_script start

            # remove the PostgreSQL database and user
            su - $postgres_user -c \
                "echo \"DROP DATABASE \\\"$ls_database\\\" \" | psql template1" \
                || echo "Couldn't drop database $ls_database.";
            su - $postgres_user -c \
                "echo \"DROP USER $ls_dbuser \" | psql template1" \
                || echo "Couldn't drop database user $ls_dbuser.";
        fi

        # remove generated files
        rm -rf $vardir/
    ;;

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

# dh_installdeb will replace this with shell code automatically
# generated by other debhelper scripts.

#DEBHELPER#

exit 0