#!/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
        # Preserve the existing signup arguments while moving it to daily.
        hourly_alerts=/etc/cron.hourly/enable_secalerts
        daily_alerts=/etc/cron.daily/enable_secalerts
        if [ -f "$hourly_alerts" ] && [ ! -L "$hourly_alerts" ] && [ -x "$hourly_alerts" ] &&
            grep -Fqx '#!/bin/bash -e' "$hourly_alerts" &&
            grep -Fqx -e 'rm -f -- "$0"' -e 'rm -f $0' "$hourly_alerts" &&
            grep -Eq '^(curl|/usr/lib/inithooks/bin/secalerts-retry) https://hub\.turnkeylinux\.org/api/server/secalerts/ ' "$hourly_alerts"; then
            if [ -e "$daily_alerts" ] || [ -L "$daily_alerts" ]; then
                chmod a-x "$hourly_alerts"
            else
                mkdir -p "${daily_alerts%/*}"
                sed -i 's|^curl https://hub\.turnkeylinux\.org/api/server/secalerts/ |/usr/lib/inithooks/bin/secalerts-retry https://hub.turnkeylinux.org/api/server/secalerts/ |' "$hourly_alerts"
                mv "$hourly_alerts" "$daily_alerts"
            fi
        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 [ -z "$2" ]; then
        # fresh install ($2 is empty) - enable services
        systemctl enable inithooks.service
        systemctl enable turnkey-init-fence.service
    fi
fi

exit 0
