#!/usr/bin/env bash
# Q002-prep.sh — hermes baseline: nginx config syntax error
#
# Prepares sc-web-server for Q002 "Syntax Error in Aisle Four".
# Introduces a deliberate nginx config syntax error that breaks the service.
#
# What this does:
#   - Installs nginx if not present
#   - Writes a broken /etc/nginx/sites-enabled/axiomworks.conf
#     (missing semicolon on the server_name line)
#   - Stops nginx so the player finds it down
#   - Adds error log evidence
#
# Idempotent: safe to run multiple times.

set -euo pipefail

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

DOMAIN="${1:-sc-web-server}"
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 "Q002-prep: Preparing $DOMAIN for 'Syntax Error in Aisle Four'..."

run_in_vm "mkdir -p /etc/nginx/sites-enabled /etc/nginx/sites-available"

# Write broken nginx config (missing semicolon after server_name)
run_in_vm "cat > /etc/nginx/sites-enabled/axiomworks.conf <<'NGINX_CONF'
server {
    listen 80;
    server_name axiomworks.internal   # <-- MISSING SEMICOLON: this is the bug
    root /var/www/axiomworks;
    index index.html;

    location / {
        try_files \$uri \$uri/ =404;
    }
}
NGINX_CONF"

# Disable the default site to make this the only relevant config
run_in_vm "rm -f /etc/nginx/sites-enabled/default"

# Stop nginx (it fails to start with bad config)
run_in_vm "systemctl stop nginx || true"

# Populate nginx error log with the kind of evidence a player would find
run_in_vm "mkdir -p /var/log/nginx && echo '[emerg] unexpected \";\" in /etc/nginx/sites-enabled/axiomworks.conf:3' >> /var/log/nginx/error.log"

# Create the web root (nginx would serve from here if config were valid)
run_in_vm "mkdir -p /var/www/axiomworks && echo '<h1>Axiom Works</h1>' > /var/www/axiomworks/index.html"

echo "Q002-prep: Done. nginx is stopped with broken config on $DOMAIN."
