#!/bin/sh

. /usr/share/debconf/confmodule

set -e

restore_old_timeouts()
{
    if [ -s /run/open-iscsi/upgrade/restore_old_timeouts ] ; then
        sh /run/open-iscsi/upgrade/restore_old_timeouts || :
    fi
    rm -f /run/open-iscsi/upgrade/restore_old_timeouts
    [ ! -d /run/open-iscsi/upgrade ] || rmdir --ignore-fail-on-non-empty /run/open-iscsi/upgrade
    [ ! -d /run/open-iscsi ] || rmdir --ignore-fail-on-non-empty /run/open-iscsi
}

case "$1" in
    configure)

        # Compatibility symlinks
        for file in iscsid iscsi_discovery iscsi-iname iscsistart; do
            if [ ! -e /usr/sbin/$file ]; then
                ln -s /sbin/$file /usr/sbin/$file
            fi
        done

        # Generate a unique iSCSI InitiatorName
        NAMEFILE=/etc/iscsi/initiatorname.iscsi
        if [ ! -e $NAMEFILE ] && [ -z "$2" ] ; then
            INAME=$(iscsi-iname -p iqn.1993-08.org.debian:01)
            if [ -n "$INAME" ] ; then
                echo "## DO NOT EDIT OR REMOVE THIS FILE!" > $NAMEFILE
                echo "## If you remove this file, the iSCSI daemon will not start." >> $NAMEFILE
                echo "## If you change the InitiatorName, existing access control lists" >> $NAMEFILE
                echo "## may reject this initiator.  The InitiatorName must be unique">> $NAMEFILE
                echo "## for each iSCSI initiator.  Do NOT duplicate iSCSI InitiatorNames." >> $NAMEFILE
                printf "InitiatorName=%s\n" "$INAME" >> $NAMEFILE
                chmod 600 $NAMEFILE
            else
                echo "Error: failed to generate an iSCSI InitiatorName, driver cannot start."
                echo
                exit 1;
            fi
        fi
    ;;

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

    *)
        echo "postinst called with unknown argument \`$1'" >&2
        exit 1
    ;;
esac

# Automatically added by dh_installinit/13.11.4
if [ "$1" = "configure" ] || [ "$1" = "abort-upgrade" ] || [ "$1" = "abort-deconfigure" ] || [ "$1" = "abort-remove" ] ; then
	if [ -x "/etc/init.d/iscsid" ]; then
		update-rc.d iscsid defaults-disabled >/dev/null || exit 1
	fi
fi
# End automatically added section
# Automatically added by dh_installinit/13.11.4
if [ "$1" = "configure" ] || [ "$1" = "abort-upgrade" ] || [ "$1" = "abort-deconfigure" ] || [ "$1" = "abort-remove" ] ; then
	if [ -x "/etc/init.d/open-iscsi" ]; then
		update-rc.d open-iscsi defaults-disabled >/dev/null || exit 1
	fi
fi
# End automatically added section
# Automatically added by dh_installsystemd/13.11.4
if [ "$1" = "configure" ] || [ "$1" = "abort-upgrade" ] || [ "$1" = "abort-deconfigure" ] || [ "$1" = "abort-remove" ] ; then
	# The following line should be removed in trixie or trixie+1
	deb-systemd-helper unmask 'iscsid.socket' >/dev/null || true

	# was-enabled defaults to true, so new installations run enable.
	if deb-systemd-helper --quiet was-enabled 'iscsid.socket'; then
		# Enables the unit on first installation, creates new
		# symlinks on upgrades if the unit file has changed.
		deb-systemd-helper enable 'iscsid.socket' >/dev/null || true
	else
		# Update the statefile to add new symlinks (if any), which need to be
		# cleaned up on purge. Also remove old symlinks.
		deb-systemd-helper update-state 'iscsid.socket' >/dev/null || true
	fi
fi
# End automatically added section
# Automatically added by dh_installsystemd/13.11.4
if [ "$1" = "configure" ] || [ "$1" = "abort-upgrade" ] || [ "$1" = "abort-deconfigure" ] || [ "$1" = "abort-remove" ] ; then
	if [ -z "${DPKG_ROOT:-}" ] && [ -d /run/systemd/system ]; then
		systemctl --system daemon-reload >/dev/null || true
		deb-systemd-invoke start 'iscsid.socket' >/dev/null || true
	fi
fi
# End automatically added section
# Automatically added by dh_installsystemd/13.11.4
if [ "$1" = "configure" ] || [ "$1" = "abort-upgrade" ] || [ "$1" = "abort-deconfigure" ] || [ "$1" = "abort-remove" ] ; then
	# The following line should be removed in trixie or trixie+1
	deb-systemd-helper unmask 'open-iscsi.service' >/dev/null || true

	# was-enabled defaults to true, so new installations run enable.
	if deb-systemd-helper --quiet was-enabled 'open-iscsi.service'; then
		# Enables the unit on first installation, creates new
		# symlinks on upgrades if the unit file has changed.
		deb-systemd-helper enable 'open-iscsi.service' >/dev/null || true
	else
		# Update the statefile to add new symlinks (if any), which need to be
		# cleaned up on purge. Also remove old symlinks.
		deb-systemd-helper update-state 'open-iscsi.service' >/dev/null || true
	fi
fi
# End automatically added section
# Automatically added by dh_installsystemd/13.11.4
if [ "$1" = "configure" ] || [ "$1" = "abort-upgrade" ] || [ "$1" = "abort-deconfigure" ] || [ "$1" = "abort-remove" ] ; then
	if [ -z "${DPKG_ROOT:-}" ] && [ -d /run/systemd/system ]; then
		systemctl --system daemon-reload >/dev/null || true
		deb-systemd-invoke start 'open-iscsi.service' >/dev/null || true
	fi
fi
# End automatically added section


if [ "$1" = configure ] && [ -n "$2" ] && [ -d /run/systemd/system ] &&
    systemctl is-active iscsid.service > /dev/null
then
    # There already is a check in preinst with a debconf prompt that
    # allows the administrator to abort. Don't abort here, because
    # leaving the package in a half-configured state is probably worse.
    # Just make sure to wait a while to see if recovery happens. If
    # not, proceed anyway.
    RETRIES=0
    while cat /sys/class/iscsi_session/session*/state 2>/dev/null | grep -qv LOGGED_IN ; do
        if [ $RETRIES -eq 0 ] ; then
            echo "open-iscsi postinst: since the check in preinst some iSCSI sessions have" >&2
            echo "                     failed. -> will wait 30s for automatic recovery" >&2
        fi
        if [ $RETRIES -gt 30 ]; then
            echo "open-iscsi postinst: some sessions are still in failed state -> iscsid" >&2
            echo "                     will be restarted regardless, since that may" >&2
            echo "                     actually help with the session recovery." >&2
            break
        fi
        RETRIES=$((RETRIES + 1))
        sleep 1
    done

    # Before we restart iscsid, we should increase the recovery timeout
    # significantly. Thanks to Mike Christie (open-iscsi upstream) for
    # the suggestion. But store the old timeouts and restore them
    # later.
    new_timeout=120
    mkdir -m 0700 -p /run/open-iscsi/upgrade
    rm -f /run/open-iscsi/upgrade/restore_old_timeouts
    trap restore_old_timeouts EXIT
    for settingfile in /sys/class/iscsi_session/session*/recovery_tmo ; do
        [ -f "${settingfile}" ] || continue
        setting="$(cat "$settingfile" 2>/dev/null || :)"
        if [ -n "$setting" ] ; then
            echo "echo "'"'"${setting}"'"'" > "'"'"${settingfile}"'" 2>/dev/null' >> /run/open-iscsi/upgrade/restore_old_timeouts
        fi
        if [ ${new_timeout} -gt ${setting} ] ; then
            echo ${new_timeout} > "${settingfile}" 2>/dev/null
        fi
    done

    # Just in case something goes wrong:
    sync

    # we want to be able to be explicit to start .service, but follow policy.d
    # therefore use deb-systemd-invoke
    deb-systemd-invoke restart iscsid.service || true

    RETRIES=0
    while cat /sys/class/iscsi_session/session*/state 2>/dev/null | grep -qv LOGGED_IN ; do
        if [ $RETRIES -eq 0 ]; then
            echo "open-iscsi postinst: after iscsid restart, waiting for iSCSI sessions" >&2
            echo "                     to recover. This may take a couple of seconds." >&2
        fi

        if [ $RETRIES -gt ${new_timeout} ]; then
            db_reset open-iscsi/upgrade_recovery_error || true
            db_input critical open-iscsi/upgrade_recovery_error || true
            db_go
            break
        fi

        RETRIES=$((RETRIES + 1))
        sleep 1
    done

    restore_old_timeouts
    trap - EXIT
fi

if [ "$1" = configure ]; then
    # With socket based activation one wants iscsid.socket to be active
    # But on upgrades the iscsid.service might already be active
    # Due to that directly starting iscsid.socket might fail:
    #   systemd[1]: iscsid.socket: Socket service iscsid.service already active, refusing.
    # Therefore check if iscsid.service is:
    # - active:
    #    - ok for now, do not start iscsid.socket as it would conflict
    #    - on a reboot .socket will be started as it is enabled
    # - inactive:
    #    - start iscsid.socket - to be ready
    # In both cases:
    #    - disable iscsid.service so it only starts by the socket after reboot
    if [ -d /run/systemd/system ]; then
        if ! systemctl is-active iscsid.service > /dev/null; then
            deb-systemd-invoke start iscsid.socket || true
        fi
    fi
fi

exit 0
