#!/usr/bin/env bash
# Q006-post-clean.sh — vulcan clean branch state after Q006
#
# Applies the authored clean outcome of Q006 so seed-vms.sh can materialize
# baseline.post-q006 for later quests.
#
# What this does:
#   - Enables and starts systemd-timesyncd
#   - Verifies archlinux-keyring is installed
#   - Replaces pacman.log failure evidence with a healthy update trail
#
# Idempotent: safe to run multiple times.

set -euo pipefail

export LIBVIRT_DEFAULT_URI="${LIBVIRT_DEFAULT_URI:-qemu:///system}"

DOMAIN="${1:-sc-build-machine}"
DRY_RUN=false
[[ "${2:-}" == "--dry-run" ]] && DRY_RUN=true

get_vm_ip() {
    local domain="$1"
    local addr=""
    addr="$(virsh domifaddr "$domain" --source agent 2>/dev/null | awk '/ipv4/ {print $4}' | cut -d/ -f1 | grep -v '^127\.' | head -n1 || true)"
    if [ -n "$addr" ]; then
        printf '%s\n' "$addr"
        return 0
    fi
    local mac=""
    mac="$(virsh dumpxml "$domain" 2>/dev/null | sed -n "s/.*<mac address='\\([^']*\\)'.*/\\1/p" | head -n1)"
    [ -n "$mac" ] || return 1
    addr="$(virsh net-dhcp-leases sc-internal 2>/dev/null | awk -v mac="$mac" '$0 ~ mac {print $5}' | cut -d/ -f1 | grep -v '^127\.' | head -n1 || true)"
    [ -n "$addr" ] || return 1
    printf '%s\n' "$addr"
}

SC_SSH_KEY="${SC_SSH_KEY:-${HOME}/.ssh/sc_host_key}"
SSH_OPTS="-o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -o BatchMode=yes -o ConnectTimeout=10 -o LogLevel=ERROR -i $SC_SSH_KEY"
VM_IP="$(get_vm_ip "$DOMAIN")"
SSH="ssh $SSH_OPTS player@$VM_IP"

run_in_vm() {
    if [ "$DRY_RUN" = "true" ]; then
        echo "  [DRY-RUN in $DOMAIN] $*"
    else
        printf '%s\n' "$*" | $SSH "sudo bash -se"
    fi
}

echo "Q006-post-clean: Applying clean Q006 outcome on $DOMAIN..."

run_in_vm "pacman -Q archlinux-keyring >/dev/null"
run_in_vm "timedatectl set-ntp true || true"
run_in_vm "systemctl enable --now systemd-timesyncd"

run_in_vm "cat > /var/log/pacman.log <<'PACMAN_LOG'
[2026-04-23T09:02:14-0400] [PACMAN] synchronizing package lists
[2026-04-23T09:02:19-0400] [ALPM] transaction started
[2026-04-23T09:02:19-0400] [ALPM] upgraded archlinux-keyring (20260401-1 -> 20260420-1)
[2026-04-23T09:02:20-0400] [ALPM] transaction completed
PACMAN_LOG"

run_in_vm "cat > /var/log/axiomworks/time-drift.note <<'NOTE'
Time sync restored.
systemd-timesyncd is enabled and active.
archlinux-keyring is present and package operations are healthy.
NOTE"

echo "Q006-post-clean: Done. systemd-timesyncd is active and baseline.post-q006 is ready on $DOMAIN."
