#!/bin/sh
# One-time backfill of cluster0 journal from known-good state (2026-06-13 session).
# Safe to re-run: appends only if journal is empty.
set -eu
ROOT="$(cd "$(dirname "$0")/.." && pwd)"
# shellcheck source=/dev/null
. "$ROOT/scripts/lib/common.sh"
ensure_shared_mounted
journal_init

if [ -f "$JOURNAL_TSV" ] && [ "$(wc -l < "$JOURNAL_TSV")" -gt 1 ]; then
  log "journal already has entries — skip backfill (see $JOURNAL_TSV)"
  sh "$ROOT/scripts/journal-rebuild-summary.sh"
  exit 0
fi

export JOURNAL_ACTOR=backfill
TS="2026-06-13T12:00:00+00:00"

append() {
  _host="$1"
  _phase="$2"
  _action="$3"
  _status="$4"
  _detail="$5"
  printf '%s\t%s\t%s\t%s\t%s\t%s\t%s\n' \
    "$TS" "$_host" "$JOURNAL_ACTOR" "$_phase" "$_action" "$_status" "$_detail" >> "$JOURNAL_TSV"
}

# Infrastructure (all nodes)
for H in cast01 cast02 cast03; do
  append "$H" baseline nfs_mount OK "/shared from FE export"
  append "$H" baseline packages OK "nginx php83-fpm mariadb-client nfs-utils"
  append "$H" baseline hosts OK "cast-cluster /etc/hosts block"
done

# MariaDB
append cast01 db mariadb-primary OK "GTID primary server-id=1"
append cast01 db load-schemas OK "16 crashes + 4 url_shortener tables"
append cast02 db mariadb-replica OK "GTID replica IO+SQL running"
append cast03 db mariadb-replica OK "GTID replica IO+SQL running"

# App + nginx
for H in cast01 cast02 cast03; do
  append "$H" app deploy-app OK "git next → android_cast/"
  append "$H" app configure-nginx OK "apps-port80.conf php83:9000"
done

# Verification
append cast01 verify verify_lab OK "mode=local"
append cast02 verify verify_lab OK "mode=local"
append cast03 verify verify_lab OK "mode=local"
append cast01 verify verify_lab OK "mode=cluster HTTP peers"
append cast01 verify verify_global START "pending DNS/FE cutover"

sh "$ROOT/scripts/journal-rebuild-summary.sh"
log "backfill_ok → $JOURNAL_TSV"
