#!/bin/bash

set -e

function separator() { local amount=79; if [[ ! -z "$1" ]]; then amount="$1"; fi; for _ in $(seq "$amount"); do printf "#"; done; printf "\n"; };
function top_hline() { printf "\n"; separator 99; }
function bot_hline() { separator 99; printf "\n"; }
function print_cmd() { printf "\n"; for command in "$@"; do printf "    $command\n"; done; printf "\n"; }

function help_not_configured() {
    top_hline
    echo "If the package configuration for 'noris-mailgrep-web' is NOT managed using ansible / puppet / etc.,"
    echo "please do it manually:"
    print_cmd "cp '/etc/noris-mailgrep-web/mailgrep-config.php.example' '/etc/noris-mailgrep-web/mailgrep-config.php'" \
              "vi '/etc/noris-mailgrep-web/mailgrep-config.php'"
    echo "Then, setup the apache2 configuration of this package:"
    print_cmd "cp '/etc/apache2/includes-intra/mailgrep-web.conf.example' '/etc/apache2/includes-intra/mailgrep-web.conf'" \
              "vi '/etc/apache2/includes-intra/mailgrep-web.conf'"
    echo "Then, reload apache:"
    print_cmd "apache2ctl -k graceful"
    bot_hline
}

case "$1" in
    configure)
        if [[ ! -f /etc/apache2/includes-intra/mailgrep-web.conf ]] \
            || grep -s -q "<mailgrep_path>" /etc/apache2/includes-intra/mailgrep-web.conf ; then
            help_not_configured
        fi

        chown --recursive www-data:www-data /etc/noris-mailgrep-web
        chmod --recursive 550               /etc/noris-mailgrep-web

        if [ -f /etc/noris-mailgrep-web/mailgrep-conf.php ]; then
            chmod 440 /etc/noris-mailgrep-web/mailgrep-conf.php
        fi

        apache2ctl -k graceful
    ;;

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

    *)
        echo "postinst 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
