#!/bin/bash 

set -e

# Source debconf library.
. /usr/share/debconf/confmodule

CONFIGFILE="/etc/alternc/local.sh"

update_var() {
    local question
    local var
    question="$1"
    var="$2"
    db_get "$question"

    grep -Eq "^ *$var=" $CONFIGFILE || echo "$var=" >> $CONFIGFILE
    SED_SCRIPT="$SED_SCRIPT;s\\^ *$var=.*\\$var=\"$RET\"\\"
}

# summary of how this script can be called:
#        * <postinst> `configure' <most-recently-configured-version>
#        * <old-postinst> `abort-upgrade' <new version>
#        * <conflictor's-postinst> `abort-remove' `in-favour' <package>
#          <new-version>
#        * <deconfigured's-postinst> `abort-deconfigure' `in-favour'
#          <failed-install-package> <version> `removing'
#          <conflicting-package> <version>
# for details, see http://www.debian.org/doc/debian-policy/ or
# the debian-policy package
#
# quoting from the policy:
#     Any necessary prompting should almost always be confined to the
#     post-installation script, and should be protected with a conditional
#     so that unnecessary prompting doesn't happen if a package's
#     installation fails and the `postinst' is called with `abort-upgrade',
#     `abort-remove' or `abort-deconfigure'.

case "$1" in
  configure)

    # ajoute l'user postfix au groupe sasl
    adduser --quiet postfix sasl

    # corriger les permissions du chroot
    mkdir -p /var/spool/postfix/var/run/saslauthd || true
    dpkg-statoverride --quiet --update --add root sasl 710 /var/spool/postfix/var/run/saslauthd  || true


    db_get "alternc/alternc_mail"
    VMAIL_HOME="$RET"
    if ! getent group vmail; then
       addgroup --gid 1998 vmail
    fi
    if ! getent passwd vmail; then
       useradd -g vmail -u 1998 vmail -d "$VMAIL_HOME" -m 
    fi 
    test -d "$VMAIL_HOME" || mkdir -p "$VMAIL_HOME"
    chown vmail:vmail "$VMAIL_HOME" 
    chown vmail:vmail "$VMAIL_HOME"/* 2>/dev/null || true # It may be empty
    chmod u+rxw "$VMAIL_HOME" 
    chmod u+rxw "$VMAIL_HOME"/* 2>/dev/null || true # It may be empty
    chmod g+rxw "$VMAIL_HOME" 
    chmod g+rxw "$VMAIL_HOME"/* 2>/dev/null || true # It may be empty

    # build local.sh if it does not exist
    if [ ! -f $CONFIGFILE ]; then
        cat > $CONFIGFILE <<EOF
#!/bin/sh
#
# AlternC - Web Hosting System - Configuration
# This file will be modified on package configuration
# (e.g. upgrade or dpkg-reconfigure alternc)

# Hosting service name
HOSTING=""

# Primary hostname for this box (will be used to access the management panel)
FQDN=""

# Public IP
PUBLIC_IP=""

# Internal IP
# (most of the time, should be equal to PUBLIC_IP, unless you are behind
# firewall doing address translation)
INTERNAL_IP=""

# Monitoring IP or network (will be allowed to access Apache status)
MONITOR_IP=""

# Primary DNS hostname
NS1_HOSTNAME=""

# Secondary DNS hostname
NS2_HOSTNAME=""

# Mail server hostname
DEFAULT_MX=""

# Secondary mail server hostname
DEFAULT_SECONDARY_MX=""

# Note: MySQL username/password configuration now stored in /etc/alternc/my.cnf

# quels clients mysql sont permis (%, localhost, etc)
MYSQL_CLIENT=""

# the type of backup created by the sql backup script
# valid options are "rotate" (newsyslog-style) or "date" (suffix is the date)
SQLBACKUP_TYPE=""

# overwrite existing files when backing up
SQLBACKUP_OVERWRITE=""

# known slave servers, empty for none, localhost is special (no ssh)
ALTERNC_SLAVES=""

# File to look at for forced launch of update_domain (use incron)
INOTIFY_UPDATE_DOMAIN="/var/run/alternc/inotify_update_domain.lock"

# File to look at for forced launch of do_actions (use incron)
INOTIFY_DO_ACTION="/var/run/alternc/inotify_do_action.lock"

# AlternC Locations
ALTERNC_HTML=""
ALTERNC_MAIL=""
ALTERNC_LOGS=""

# Custom directory for archived logs. ALTERNC_LOGS is used by default to view logs files on the panel.
# But you may merge your logs in other directory. In order to view them,
# Uncomment and complete the following variable to use it instead of ALTERNC_LOGS.
#ALTERNC_LOGS_ARCHIVE=""
 
EOF

        chown root:alterncpanel $CONFIGFILE
        chmod 640 $CONFIGFILE
    fi

    # Update local.sh
    # 1. use cp to keep permissions
    # 2. add missing variable to local.sh
    # 3. use sed to set variables with current values
    echo "Updating $CONFIGFILE"
    cp -a -f $CONFIGFILE $CONFIGFILE.tmp
    # SED_SCRIPT will be modified by update_var
    SED_SCRIPT=""
    update_var alternc/hostingname HOSTING
    update_var alternc/desktopname FQDN 
    update_var alternc/public_ip PUBLIC_IP
    update_var alternc/internal_ip INTERNAL_IP
    update_var alternc/monitor_ip MONITOR_IP
    update_var alternc/ns1 NS1_HOSTNAME
    update_var alternc/ns2 NS2_HOSTNAME
    update_var alternc/default_mx DEFAULT_MX 
    update_var alternc/default_mx2 DEFAULT_SECONDARY_MX
    update_var alternc/mysql/client MYSQL_CLIENT 
    update_var alternc/sql/backup_type SQLBACKUP_TYPE
    update_var alternc/sql/backup_overwrite SQLBACKUP_OVERWRITE
    update_var alternc/slaves ALTERNC_SLAVES
    update_var alternc/alternc_html ALTERNC_HTML
    update_var alternc/alternc_mail ALTERNC_MAIL
    update_var alternc/alternc_logs ALTERNC_LOGS
    sed -e "$SED_SCRIPT" < $CONFIGFILE > $CONFIGFILE.tmp
    mv -f $CONFIGFILE.tmp $CONFIGFILE

    # Erase all apacheconf file
    # They will be regenerated without the bug by upgrade_check.sh below.
    if dpkg --compare-versions "$2" le "0.9.3.9-globenet14"; then
        rm -f /var/alternc/apacheconf/*/*  # Old AlternC version
    fi

    echo "checking for upgrades"
    /usr/share/alternc/install/upgrade_check.sh $2

    # Setup grants
    db_get "alternc/mysql/host"
    MYSQL_HOST="$RET"
    if [ "$MYSQL_HOST" != "localhost" -o -e /usr/sbin/mysqld ]; then
        # compatibility shims with my.cnf
        host="$RET"
        db_get "alternc/mysql/db"
        database="$RET"
        db_get "alternc/mysql/user"
        user="$RET"
        db_get "alternc/mysql/password"
        password="$RET"
        db_get "alternc/mysql/alternc_mail_user"
        alternc_mail_user="$RET"
        db_get "alternc/mysql/alternc_mail_password"
        alternc_mail_password="$RET"

        # we source (instead of forking) mysql.sh so that it gets the local environment above
        . /usr/share/alternc/install/mysql.sh
    fi

    if [ -e $CONFIGFILE ]; then
      # source local.sh variables
      . $CONFIGFILE
    fi

    # multi-server configuration: we create an alternc account with
    # authorized keys. since this is the master, we do not give him a
    # valid shell, but we still need the user for proper perms
    ALTERNC_USER_HOME="$ALTERNC_HTML"
    if [ ! -z "$ALTERNC_SLAVES" ] && [ "$ALTERNC_SLAVES" != "localhost" ] ; then
        if ! grep -q alternc /etc/passwd ; then
            echo "Creating alternc account"
            adduser --quiet --system --uid 342 --home $ALTERNC_HTML --shell /bin/false --ingroup adm alternc
        fi
        chown alternc "$ALTERNC_USER_HOME"
        if [ -r ~root/.ssh/id_dsa.pub ]; then
            key=`cat ~root/.ssh/id_dsa.pub`
            if ! grep -q "$key" $ALTERNC_USER_HOME/.ssh/authorized_keys ; then
                echo "Authorizing root ssh key to access the common alternc account"
                mkdir -p $ALTERNC_USER_HOME/.ssh
                echo "$key" >> $ALTERNC_USER_HOME/.ssh/authorized_keys
                chown -R alternc:adm $ALTERNC_USER_HOME/.ssh
                chmod -R og-rwx $ALTERNC_USER_HOME/.ssh
            fi
        else
            echo "No SSH key in "~root/.ssh/id_dsa.pub
            echo "create one and reconfigure alternc to propagate SSH keys"
        fi
    else
        echo "AlternC slaves not configured ($ALTERNC_SLAVES)"
    fi

    # /var/alternc/dns/d/www.example.com
    FQDN_LETTER="`echo $FQDN | sed -e 's/.*\.\([^\.]\)[^\.]*\.[^\.]*$/\1/'`"
    if [ "$FQDN_LETTER" = "$FQDN" ]
    then
           FQDN_LETTER="_"
    fi

    #clean old access to the management panel
    # We don't use this anymore : (FIXME : shall we remove /var/alternc/dns while upgrading ?)
    #find /var/alternc/dns/ -type l -lname /var/alternc/bureau -exec rm {} \;

    # Bind stuff
    touch           /var/lib/alternc/bind/automatic.conf /var/lib/alternc/bind/slaveip.conf
    chown root:bind /var/lib/alternc/bind/automatic.conf /var/lib/alternc/bind/slaveip.conf
    chmod 640       /var/lib/alternc/bind/automatic.conf /var/lib/alternc/bind/slaveip.conf
    mkdir -p /var/run/alternc && chown alterncpanel:alterncpanel /var/run/alternc
    touch /var/run/alternc/refresh_slave
    /usr/lib/alternc/slave_dns
    # Apache will not start without this file
    touch /var/lib/alternc/apache-vhost/vhosts_all.conf

	#sudo stuff allowing alterncpanel to use quota
	if [ -d /etc/sudoers.d ]; then
		cp /etc/alternc/alternc-sudoers /etc/sudoers.d/alternc-sudoers
		chmod 0440 /etc/sudoers.d/alternc-sudoers
		if ! grep -q '#includedir /etc/sudoers.d' "/etc/sudoers"; then
			echo "*************************************************"
                        echo "*                                               *"
    			echo "*             /!\ WARNING /!\                   *"
    			echo "* Please add yourself the following directive : *"
			echo "*        #includedir /etc/sudoers.d             *"
			echo "* in file /etc/sudoers   (use visudo command)   *"
			echo "* Else you'll have troubles with some features  *"
			echo "*                 of AlternC                    *"
                        echo "*                                               *"
    			echo "*************************************************"
		fi
	else
		echo "running an older version of sudo"
		#FIXME
		echo "copy content of /usr/share/doc/examples/example.sudoers into /etc/sudoers.d to run properly"
	 fi

    # important: postinst freezes without that:
    db_stop

    # instead of preinst, we launch it here : 
    /usr/lib/alternc/fixperms.sh
    echo "**********************************************"
    echo "*                                            *"
    echo "* /!\                                    /!\ *"
    echo "*                 ALTERNC:                   *"
    echo "* Please run alternc.install to fully deploy *"
    echo "*                                            *"
    echo "*                                            *"
    echo "*                                            *"
    echo "**********************************************"
    ;;

    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#

# important: postrm freezes withtout that:
db_stop

exit 0

# vim: et sw=4