#!/bin/sh
# preinst script for #PACKAGE#
#
# see: dh_installdeb(1)

set -e

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


case "$1" in
    install|upgrade)
    if [ -e /etc/apache2/sites-enabled/000-default ]; then
        echo "Deactivating default site on apache"
        rm /etc/apache2/sites-enabled/000-default
        FLAG=1
    fi
    if [ -e /etc/apache2/sites-enabled/ngcp-www-csc ]; then
    	echo "Deactivating ngcp-www-csc on apache"
    	rm /etc/apache2/sites-enabled/ngcp-www-csc
        FLAG=1
    fi
    if [ -e /etc/apache2/ports.conf ]; then
        if grep '^[[:space:]]*Listen 443' \
                /etc/apache2/ports.conf &> /dev/null \
            ||  grep '^[[:space:]]*Listen 80' \
                /etc/apache2/ports.conf &> /dev/null; then
            echo "Apache must not listen on 80 or 443 ports"
            echo "Commenting 80/443 ports from /etc/apache2/ports.conf"
            # don't listen on 80 or 443
            sed -e 's/^[[:space:]]*Listen 443/#Listen 443/' \
                -e 's/^[[:space:]]*Listen 80/#Listen 80/' \
                -e 's/^[[:space:]]*NameVirtualHost \*:80/#NameVirtualHost \*:80/' \
                -i /etc/apache2/ports.conf
            FLAG=1
        fi
    fi
    if dpkg-maintscript-helper supports rm_conffile 2>/dev/null; then
        dpkg-maintscript-helper rm_conffile \
        /etc/ngcp-config/templates/etc/apache2/sites-available/ngcp-www-csc.tt2 \
         -- "$@"
        dpkg-maintscript-helper rm_conffile \
        /etc/ngcp-config/templates/etc/lsb_scripts/ngcp-www-csc.tt2 \
         -- "$@"
        dpkg-maintscript-helper rm_conffile \
        /etc/ngcp-config/templates/etc/lsb_scripts/ngcp-www-csc.services \
         -- "$@"
    fi
    # fix tmp perms
    if [ -d /tmp/csc ]; then
        echo "fixing /tmp/csc dir perms"
        chown -R www-data:www-data /tmp/csc
    fi
    ;;

    abort-upgrade)
    ;;

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

if [ -n "$FLAG" ]; then
    # restart apache
    if [ -x /etc/init.d/apache2 ]; then
      if [ -x "`which invoke-rc.d 2>/dev/null`" ]; then
        invoke-rc.d apache2 restart|| true
      else
        /etc/init.d/apache2 restart || true
      fi
    fi
fi

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

#DEBHELPER#

exit 0
