#!/usr/bin/env bash
# Verify the v107 boot orchestrator + watchdog installation took effect.
# Self-heals by re-running the v107 installers if either is missing.
#
# Rationale: v107's first deploy to staging failed in apply-scripts.sh due to
# the dangerous-pattern regex matching a docker template flag in the migrate
# script. The script text was patched in place; this v108 script is a
# defence-in-depth check so that any host that picked up v107 mid-fail
# converges to the intended state.

set -euo pipefail

V107_DIR=/root/whp/scripts/updates/2026.05.107

echo "Verifying boot orchestrator + watchdog installation..."

ok=1

if systemctl is-enabled whp-boot-orchestrator.service >/dev/null 2>&1; then
    echo "  ok  whp-boot-orchestrator.service enabled"
else
    echo "  miss whp-boot-orchestrator.service NOT enabled — re-running ${V107_DIR}/setup-boot-orchestrator.sh"
    if [ -x "${V107_DIR}/setup-boot-orchestrator.sh" ]; then
        bash "${V107_DIR}/setup-boot-orchestrator.sh"
    else
        echo "  FAIL ${V107_DIR}/setup-boot-orchestrator.sh missing or not executable"
        ok=0
    fi
fi

if crontab -l 2>/dev/null | grep -qF customer-container-watchdog.sh; then
    echo "  ok  customer-container-watchdog cron installed"
else
    echo "  miss customer-container-watchdog cron NOT installed — re-running ${V107_DIR}/setup-customer-watchdog.sh"
    if [ -x "${V107_DIR}/setup-customer-watchdog.sh" ]; then
        bash "${V107_DIR}/setup-customer-watchdog.sh"
    else
        echo "  FAIL ${V107_DIR}/setup-customer-watchdog.sh missing or not executable"
        ok=0
    fi
fi

if command -v jq >/dev/null 2>&1 && [ -f /docker/whp/settings.json ]; then
    bo_ok=$(jq -r '.boot_orchestrator // empty' /docker/whp/settings.json)
    if [ -n "${bo_ok}" ]; then
        echo "  ok  settings.json has boot_orchestrator block"
    else
        echo "  miss settings.json missing boot_orchestrator — re-running ${V107_DIR}/seed-boot-orchestrator-settings.sh"
        if [ -x "${V107_DIR}/seed-boot-orchestrator-settings.sh" ]; then
            bash "${V107_DIR}/seed-boot-orchestrator-settings.sh"
        else
            echo "  FAIL ${V107_DIR}/seed-boot-orchestrator-settings.sh missing"
            ok=0
        fi
    fi
fi

if [ "${ok}" = "1" ]; then
    echo "Boot orchestrator + watchdog: installation verified."
    exit 0
else
    echo "Boot orchestrator + watchdog: at least one component could not be installed."
    exit 1
fi
