#!/usr/bin/env bash
# Q006-prep.sh — vulcan baseline: time sync disabled, pacman signature errors logged
#
# Prepares sc-build-machine for Q006 "Time Is A Flat Circle".
# The machine clock is drifting because time sync was disabled, which surfaces
# as pacman signature verification failures.
#
# What this does:
#   - Disables and stops common NTP services
#   - Seeds pacman.log with realistic signature failure evidence
#   - Leaves a small operator note pointing at time drift symptoms
#
# 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-prep: Preparing $DOMAIN for 'Time Is A Flat Circle'..."

run_in_vm "timedatectl set-ntp false || true"
run_in_vm "systemctl stop systemd-timesyncd ntpd chronyd 2>/dev/null || true"
run_in_vm "systemctl disable systemd-timesyncd ntpd chronyd 2>/dev/null || true"
run_in_vm "mkdir -p /var/log/axiomworks /srv/repo /srv/builds"

run_in_vm "cat > /var/log/pacman.log <<'PACMAN_LOG'
[2026-04-23T08:10:51-0400] [PACMAN] synchronizing package lists
[2026-04-23T08:10:57-0400] [ALPM] transaction started
[2026-04-23T08:10:58-0400] [ALPM] warning: Public keyring not found; have you run 'pacman-key --init'?
[2026-04-23T08:10:58-0400] [ALPM] error: archlinux-keyring: signature from \"Arch Linux Master Key\" is invalid
[2026-04-23T08:10:58-0400] [ALPM] error: failed to commit transaction (invalid or corrupted package (PGP signature))
[2026-04-23T08:10:58-0400] [ALPM] transaction failed
PACMAN_LOG"

run_in_vm "cat > /var/log/axiomworks/time-drift.note <<'NOTE'
Builds started failing after the machine clock fell behind.
Symptoms:
  - pacman reports invalid or corrupted package (PGP signature)
  - signed packages appear to come from the future
  - timedatectl shows NTP inactive
NOTE"

echo "Q006-prep: Done. NTP is disabled and pacman signature failures are seeded on $DOMAIN."
