#!/bin/bash
# postinst script for xivo-config
#
# see: dh_installdeb(1)

LIBDIR="/var/lib/xivo-config"

generate_tls_keys() {
    KEYDIR=/etc/asterisk/keys
    KEYGEN=/usr/sbin/ast_tls_cert
    local force="${1}"


    mkdir -p ${KEYDIR}

    if [ ! -d "${KEYDIR}" ]; then
        echo Unable to create $KEYDIR - aborting generating new keys
        return 1
    fi

    if [ -n "${force}" ]; then
        # If force, remove the old keys
        rm -f ${KEYDIR}/*
    elif [ "$(ls -A ${KEYDIR})" ]; then
        echo $KEYDIR is not empty - aborting generating new keys
        return 2
    fi

    cd ${KEYDIR}
    ${KEYGEN} -C `hostname` -O `hostname` -d ${KEYDIR}
    chown -R asterisk:asterisk /etc/asterisk/keys
}

generate_ari_password() {
    ARI_CONF="/etc/asterisk/ari.conf"
    ARI_PASSWORD=$(< /dev/urandom tr -dc A-Za-z0-9 | head -c${1:-16};)
    sed -i "s/password = Nasheow8Eag/password = ${ARI_PASSWORD}/" $ARI_CONF
}

register_first_asterisk_conf_before_enabling_dialplan_templating() {
    cp -R /usr/share/xivo-config/templates/dialplan/* /usr/share/xivo-config/dialplan/
}

case "$1" in
    configure)

        if [ -z "$2" ] || dpkg --compare-versions "$2" "<<" "2024.08.00"; then
			register_first_asterisk_conf_before_enabling_dialplan_templating
		fi

        # remove old file, replaced in the new version
        old_modprobe_xivo_file="/etc/modprobe.d/xivo"
        if [ -f $old_modprobe_xivo_file ]; then
            rm $old_modprobe_xivo_file
        fi

        if [ -d /usr/share/xivo-config/datastorage ]; then
            rm -rf /usr/share/xivo-config/datastorage
        fi

        if dpkg --compare-versions "$2" "le-nl" "16.10~20160801.134640.fb558cc"; then
            # remove files that should never have been created
            rm -f /default /init /odbc.ini.template /odbcinst.ini.template /openssl-x509.conf
        fi

        # keep cert/private key only if they changed. We don't want to keep the one
        # whose private key has been published.
        # *.dpkg-backup only exist if the conffile was modified
        # We use cp because old_key and old_cert may be symlinks

        old_key=/etc/nginx/ssl/server.key.dpkg-backup
        old_cert=/etc/nginx/ssl/server.crt.dpkg-backup
        new_key=/usr/share/xivo-certs/server.key
        new_cert=/usr/share/xivo-certs/server.crt
        if [ -d /etc/nginx/ssl ] ; then
            [ -e "$old_key" ] && cp "$old_key" "$new_key"
            [ -e "$old_cert" ] && cp "$old_cert" "$new_cert"
            rm -f "$old_key" "$old_cert"
            rmdir --ignore-fail-on-non-empty /etc/nginx/ssl
        fi

        # generate X.509 certificates if necessary. Valid for 10 years.
        config=/usr/share/xivo-config/x509/openssl-x509.conf
        if [ ! -e "$new_key" -o ! -e "$new_cert" ] ; then
            openssl req -x509 -sha256 -nodes -days 3650 -newkey rsa:2048 -config "$config" -keyout "$new_key" -out "$new_cert"
        fi

        # ensure ownership and permissions
        chown root:www-data "$new_key" "$new_cert"
        chmod 640 "$new_key" "$new_cert"

        # ODBC configuration
        odbcinst -i -s -f /usr/share/xivo-config/odbc/odbc.ini.template -l -v
        xivo-update-odbcinst-config
        if dpkg --compare-versions "$2" "le-nl" "16.10~20160725.191447.46342d0" && [ -d /var/spool/asterisk ]; then
            # remove files created by erroneous odbc configuration
            find /var/spool/asterisk -maxdepth 1 -type f -regex '/var/spool/asterisk/[0-9]+\.log' -delete
        fi

        if [ -f "/etc/nginx/sites-available/xivo-restapi" ]; then
            rm -f "/etc/nginx/sites-available/xivo-restapi"
        fi

        # reload templated config on install/upgrade before asterisk launch
        xivo-update-config

        # run asterisk configuration
        /usr/share/asterisk/bin/asterisk_fix

        # interaction with asterisk
        usermod -a -G www-data asterisk
        usermod -a -G asterisk www-data

        # remove nginx default
        nginx_default='/etc/nginx/sites-enabled/default'
        if [ -f $nginx_default ]; then
            rm -f $nginx_default
        fi

        # ensure /dev/dahdi is owned by asterisk
        if [ -x /etc/init.d/dahdi ]; then
            invoke-rc.d asterisk stop
            invoke-rc.d dahdi stop
            udevadm control --reload-rules
        fi
        # Need to restart this services for updating fail2ban configuration
        if [ -x /etc/init.d/rsyslog ]; then
            invoke-rc.d rsyslog restart
        fi

        # prevent errors from being displayed at installation or upgrade
        if [ ! -f /var/log/asterisk/fail2ban ]; then
            touch /var/log/asterisk/fail2ban
            chown asterisk:asterisk /var/log/asterisk/fail2ban
            chmod 660 /var/log/asterisk/fail2ban
        fi
        if [ ! -f /var/log/xivo-provd-fail2ban.log ]; then
            touch /var/log/xivo-provd-fail2ban.log
        fi
        invoke-rc.d fail2ban reload

        # load sysctl rules if exist
        find /etc/sysctl.d -type f -name '*.conf' -exec sysctl -q -p {} \;

        xivo-fix-paths-rights

        if [ -z $2 ]; then
          # Clean install
          generate_tls_keys
        fi
        if dpkg --compare-versions "$2" "lt-nl" "2022.04.01"; then
            # Upgrade to 2022.04 (Deb11)
            generate_tls_keys "force"
        fi
        generate_ari_password

    ;;
    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#

sed -i 's#/etc/pf-xivo#/etc/xivo#' /etc/xivo/asterisk/xivo_fax.conf
sed -i 's#/etc/xivo/mail.txt#/etc/xivo/asterisk/mail.txt#' /etc/xivo/asterisk/xivo_fax.conf

exit 0
