#!/bin/sh
# preinst script for eole-common-pkg
#
# see: dh_installdeb(1)

set -e

# summary of how this script can be called:
#        * <new-preinst> `install'
#        * <new-preinst> `install' <old-version>
#        * <new-preinst> `upgrade' <old-version>
#        * <old-preinst> `abort-upgrade' <new-version>
# for details, see https://www.debian.org/doc/debian-policy/ or
# the debian-policy package


install_policy_script() {
    if ! grep -qs skip_disabled /usr/sbin/policy-rc.d
    then
        return 0
    fi

    cat > /usr/sbin/policy-rc.d <<'EOF'
#!/bin/sh

# Do not execute action for disabled service
skip_disabled() {
    if [ -d /run/systemd ] && ! systemctl is-enabled "${1}" > /dev/null 2>&1
    then
        # OK, do not run
        exit 101
    else
        # OK, run
        exit 104
    fi
}

case "${1}-${2}" in
    freeradius-*reload)
        # https://bugs.launchpad.net/ubuntu/+source/freeradius/+bug/1712817
        skip_disabled "${1}"
        ;;
    salt-master-*restart*)
        # The service is disabled by EOLE because we use other names
	# systemd service pass action between parenthesis in ${2}
        skip_disabled "${1}"
        ;;
    *)
        # OK, run
        exit 104
        ;;
esac
EOF
    chmod +x /usr/sbin/policy-rc.d
}

case "$1" in
    install|upgrade)
        # Workaround https://dev-eole.ac-dijon.fr/issues/21207
        install_policy_script
    ;;

    abort-upgrade)
    ;;

    *)
        echo "preinst 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
