#!/bin/sh
set -eu

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

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

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


    echo "flush"
    flush
    echo "setup_config"
    setup_config
    echo "flush"
    flush

    echo "systemctl restart ferm.service"
    systemctl restart ferm.service
    echo "systemctl is-active --quiet 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
    echo "while ! systemctl is-active --quiet ferm-early.service"
    while ! systemctl is-active ferm-early.service; do
        sleep 0.2
        i=$((i+1))
        if [ "$i" -gt 50 ]; then
            echo >&2 "ERROR: ferm-early.service did not start after boot"
            systemctl status ferm-early.service --no-pager || true
            journalctl --boot --unit=ferm-early.service
            exit 1
        fi
    done
    echo "while ! systemctl is-active --quiet ferm.service"
    while ! systemctl is-active ferm.service; do
        sleep 0.2
        i=$((i+1))
        if [ "$i" -gt 50 ]; then
            echo >&2 "ERROR: ferm.service did not start after boot"
            systemctl status ferm.service --no-pager || true
            journalctl --boot --unit=ferm.service
            exit 1
        fi
    done
    if [ -n "${TESTDEBUG:-}" ]; then
        cat /etc/ferm/ferm.conf
        systemctl status ferm-early.service --no-pager
        journalctl --boot --unit=ferm-early.service
        systemctl status ferm.service --no-pager
        journalctl --boot --unit=ferm.service
        show afterboot
        systemctl restart ferm.service --no-pager
        systemctl status ferm.service --no-pager
        show afterrestart
        ferm --lines /etc/ferm/ferm.conf 2>/dev/null
        show afterferm-lines
        ferm /etc/ferm/ferm.conf 2>/dev/null
        show afterferm
    fi
fi

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

echo "check_present"
check_present

echo "systemctl stop ferm.service"
systemctl stop ferm.service
echo "check_absent"
check_absent

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

exit 0

