#!/bin/sh

set -e

# Uses debconf
. /usr/share/debconf/confmodule

CONFIGFILE="/etc/alternc/local.sh"
MENUFILE="/etc/alternc/menulist.txt"
APACHEROTATE="/etc/logrotate.d/apache"

# Add awstats include to the apache configuration file given as argument
function configure {
    if ! grep -Eq "\*\*\*AWSTATS\*\*\*" $1; then
	cp -a -f $1 $1.tmp
	sed -e "s/\*\*\*ALTERNC_ALIASES\*\*\*/&\\
	    # ***AWSTATS*** \\
	Include \"\/etc\/apache\/alternc-awstats.conf\"/" < $1 > $1.tmp
	mv -f $1.tmp $1
    fi
}
# Configure logrotate.d/apache to create log owned by group www-data : 
function logrotate_apache {
        cp -a -f $APACHEROTATE $APACHEROTATE.tmp
        sed -e 's/create 640 root adm/create 640 root www-data/' < $APACHEROTATE > $APACHEROTATE.tmp 
        mv -f $APACHEROTATE.tmp $APACHEROTATE
}

case "$1" in
  configure)
    . "$CONFIGFILE"

    # Then, configure the quota for "aws"
    db_get alternc-awstats/default_quota_value || true
    /usr/lib/alternc/quota_init aws $RET

    db_stop

    echo "Installing mysql table"
    mysql -h"$MYSQL_HOST" -p"$MYSQL_PASS" -u"$MYSQL_USER" "$MYSQL_DATABASE" \
	</usr/share/alternc/awstats.sql || true
    
    # Refresh apache configuration
    configure /etc/alternc/templates/apache/httpd.conf
    configure /etc/alternc/templates/apache-ssl/httpd.conf
    ln /usr/lib/cgi-bin/awstats.pl /var/alternc/cgi-bin/ -sf 
    alternc.install

    logrotate_apache
    # Process the language compilation.
    /usr/share/alternc/install/dopo.sh
    
    # Add htpasswd : 
    touch /etc/alternc/awstats.htpasswd
    chown www-data /etc/alternc/awstats.htpasswd /etc/awstats
    chmod 644 /etc/alternc/awstats.htpasswd 
    chmod 755 /etc/awstats

    # ADD menu item : 
    if ! grep -q "^menu_aws.php$" "$MENUFILE"; then
        rm -f $MENUFILE.alternc_awstats
        sed -e "s/menu_brouteur.php/&\\
menu_aws.php/" <$MENUFILE >$MENUFILE.alternc_awstats
        mv -f $MENUFILE.alternc_awstats $MENUFILE
    fi
    ;;

  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#

# vim: et sw=4
