#!/bin/sh

set -e

chmod 755 /usr/lib/python3/dist-packages/libinithooks/inithooks_cache.py

if [ "$1" = "configure" ] || [ "$1" = "abort-upgrade" ] \
        || [ "$1" = "abort-deconfigure" ] || [ "$1" = "abort-remove" ] ; then
    if [ "$1" = "configure" ]; then
        # Existing links keep their schedules and credentials when the helper
        # is renamed. Leave locally replaced units and commands alone.
        for job in retry dns; do
            unit="/etc/systemd/system/turnkey-mail-$job.service"
            command=retry
            [ "$job" != dns ] || command=dns-update
            old="ExecStart=/usr/lib/inithooks/bin/turnkey-mail $command"
            new="ExecStart=/usr/lib/inithooks/bin/turnkey-hub $command"
            if [ -f "$unit" ] && [ ! -L "$unit" ] && grep -Fqx "$old" "$unit"; then
                sed -i "s|^$old\$|$new|" "$unit"
            fi
        done
    fi
    if [ "$1" = configure ]; then
        unit=/etc/systemd/system/turnkey-mail-retry.service
        if [ -f "$unit" ] && [ ! -L "$unit" ] &&
            grep -Fqx 'ExecStart=/usr/lib/inithooks/bin/turnkey-hub retry' "$unit"; then
            systemctl disable --now turnkey-mail-retry.timer >/dev/null 2>&1 || true
        fi
        cron=/etc/cron.d/turnkey-mail-retry
        if [ -f "$cron" ] && [ ! -L "$cron" ] &&
            grep -Fqx '* * * * * root /usr/lib/inithooks/bin/turnkey-hub retry >/dev/null 2>&1' "$cron"; then
            rm -f "$cron"
        fi
    fi
    systemctl daemon-reload >/dev/null || true
    # Firstboot runs package upgrades itself. Restarting initialization or
    # its console here can kill dpkg before configuration has completed.
    # Existing services use the updated scripts on their next invocation.
    rm -f /run/inithooks-was-active /run/turnkey-init-fence-was-active
    if [ "$1" = "configure" ]; then
        systemctl enable turnkey-onboarding.timer
        systemctl enable turnkey-hub-provision.timer
    fi
    if [ -z "$2" ]; then
        # fresh install ($2 is empty) - enable services
        systemctl enable inithooks.service
        systemctl enable turnkey-init-fence.service
    fi
fi

exit 0
