#!/bin/sh
# postinst script for mongooseim
#
# see: dh_installdeb(1)

set -e

# 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>
#        * <postinst> `abort-remove'
#        * <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

NAME="mongooseim"
PKG_ROOT="/usr/lib/${NAME}"

MIM_CTL="/usr/bin/mongooseimctl"

ETC_DIR="/etc/${NAME}"

VAR_LIB="/var/lib/${NAME}"
VAR_LOCK="/var/lock/${NAME}"
VAR_LOG="/var/log/${NAME}"

. /usr/share/debconf/confmodule

setup()
{
	if ! dpkg-statoverride --list $PKG_ROOT >/dev/null; then
		chown -R $NAME:$NAME $PKG_ROOT $MIM_CTL $ETC_DIR $VAR_LIB $VAR_LOCK $VAR_LOG
	fi
	#sed -i -e "s*\(RUNNER_SCRIPT_DIR=\).\**\1${PKG_ROOT}bin*" /usr/sbin/mongooseimctl

    OS_ID=$(grep ^ID= /etc/os-release | cut -d= -f2 | tr -d '"')
    OS_VERSION=$(grep ^VERSION_ID= /etc/os-release | cut -d= -f2 | tr -d '"' | cut -d. -f1)
    if { [ "$OS_ID" = "ubuntu" ] && [ "$OS_VERSION" -lt 22 ]; } || \
       { [ "$OS_ID" = "debian" ] && [ "$OS_VERSION" -lt 12 ]; }; then
        SYSTEM_OPENSSL=$(ldconfig -p | grep "libssl.so.3" | awk '{print $NF}' | head -n 1)
        if [ -z "$SYSTEM_OPENSSL" ]; then
                if [ -d /opt/mongooseim/openssl/lib64 ]; then
                    echo "/opt/mongooseim/openssl/lib64" > /etc/ld.so.conf.d/mongooseim-openssl.conf
                else
                    echo "/opt/mongooseim/openssl/lib" > /etc/ld.so.conf.d/mongooseim-openssl.conf
                fi
            ldconfig
        fi
    fi
}

case "$1" in
    configure)
	useradd --system --shell /bin/sh --home-dir $PKG_ROOT $NAME
	setup "$@"
    ;;

    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
