#!/usr/bin/env bash
# The continuous half of root config must stay continuous: idempotent, no reboot,
# and never able to acquire a destructive step by inheritance from apply.sh.
set -uo pipefail

MOD="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
SCRIPT="$MOD/host-config/converge-safe.sh"
fail=0
t() { if [ "$2" = "$3" ]; then printf 'ok    %s\n' "$1"; else printf 'FAIL  %s: expected %s, got %s\n' "$1" "$2" "$3"; fail=$((fail + 1)); fi; }

work="$(mktemp -d)"; trap 'rm -rf "$work"' EXIT

# 1. Destructive verbs must never appear in the continuous path. apply.sh legitimately
#    carries them; this file must not, however it is later edited.
for verb in mkfs sfdisk wipefs parted reboot shutdown 'watchdog' 'sshd' 'ListenAddress'; do
  if grep -qE "^[^#]*\b${verb}" "$SCRIPT"; then
    printf 'FAIL  converge-safe invokes a provisioning-only step: %s\n' "$verb"
    fail=$((fail + 1))
  fi
done
printf 'ok    converge-safe carries no destructive step\n'

# 2. It writes the declared files when they are absent or wrong, and reports it.
first=$(CONVERGE_SAFE_DRY_RUN=1 CONVERGE_SAFE_SYSCTL_DIR="$work/sysctl.d" \
  CONVERGE_SAFE_JOURNALD_DIR="$work/journald.conf.d" bash "$SCRIPT" 2>&1)
case "$first" in
  *"WOULD $work/sysctl.d/"*) ;;
  *) printf 'FAIL  missing sysctl drop-in not reported: %s\n' "$first"; fail=$((fail + 1)) ;;
esac
case "$first" in
  *"WOULD $work/journald.conf.d/"*) ;;
  *) printf 'FAIL  missing journald drop-in not reported\n'; fail=$((fail + 1)) ;;
esac
t "a dry run changes nothing on disk" "absent" \
  "$([ -e "$work/sysctl.d" ] && echo present || echo absent)"

# 3. Converged input is a no-op: every declared file already byte-identical reports OK
#    and nothing as changed. This is what makes it safe to run on every pass.
mkdir -p "$work/sysctl.d" "$work/journald.conf.d"
cp "$MOD"/host-config/sysctl.d/* "$work/sysctl.d/"
cp "$MOD"/host-config/journald.conf.d/* "$work/journald.conf.d/"
second=$(CONVERGE_SAFE_DRY_RUN=1 CONVERGE_SAFE_SYSCTL_DIR="$work/sysctl.d" \
  CONVERGE_SAFE_JOURNALD_DIR="$work/journald.conf.d" bash "$SCRIPT" 2>&1)
case "$second" in
  *"WOULD "*) printf 'FAIL  a converged host still reports pending writes\n'; fail=$((fail + 1)) ;;
esac
t "a converged host reports no change" "sysctl_changed=0 journald_changed=0" \
  "$(printf '%s' "$second" | grep -o 'sysctl_changed=[01] journald_changed=[01]')"

# 4. Drift in a declared value is detected, not silently accepted.
printf 'kernel.panic = 10\n' > "$work/sysctl.d/99-buildbox-failsafe.conf"
third=$(CONVERGE_SAFE_DRY_RUN=1 CONVERGE_SAFE_SYSCTL_DIR="$work/sysctl.d" \
  CONVERGE_SAFE_JOURNALD_DIR="$work/journald.conf.d" bash "$SCRIPT" 2>&1)
t "drifted content is detected" "sysctl_changed=1 journald_changed=0" \
  "$(printf '%s' "$third" | grep -o 'sysctl_changed=[01] journald_changed=[01]')"

[ "$fail" = 0 ] || { printf '\n%d failed\n' "$fail"; exit 1; }
printf '\nall passed\n'
