#!/bin/sh
set -eu

. "$(dirname "$0")/ferm-lib.sh"

# ------------------------------------------------------------
# PRE-REBOOT PHASE
# ------------------------------------------------------------

if [ -z "${AUTOPKGTEST_REBOOT_MARK:-}" ]; then
    echo "=== BUILD CONFIG AND START ==="


    setup_config
    ferm --flush /etc/ferm/ferm.conf

    systemctl restart ferm.service
    systemctl is-active --quiet ferm.service
else
    echo "=== POST-REBOOT PHASE, WAIT FOR INIT TO FINISH ==="

    systemctl is-system-running --wait --quiet || true

    # wait until systemd has auto-started the service
    i=0
    while ! systemctl is-active --quiet ferm.service; do
        sleep 0.2
        i=$((i+1))
        if [ "$i" -gt 50 ]; then
            echo "ERROR: ferm.service did not start after boot"
            systemctl status ferm.service --no-pager || true
            exit 1
        fi
    done
fi

echo "=== CHECK SUCCESSFUL START ==="

check_present

systemctl stop ferm.service
check_absent

if [ -z "${AUTOPKGTEST_REBOOT_MARK:-}" ] && [ "${MODE:-basic}" = "reboot" ]; then
    echo "=== systemctl reboot ==="
    autopkgtest-reboot ferm-systemd-reboot
    exit 0
fi

exit 0

