#!/usr/bin/env bash
# Q004-prep.sh — hermes baseline: web root owned by root, deploy script in place
#
# Prepares sc-web-server for Q004 "Not My Files".
# A bad deploy re-ran as root and chowned the web root to root.
# The deploy script itself is in /opt/deploy/deploy.sh.
#
# What this does:
#   - Chowns /var/www/axiomworks and all contents to root:root
#   - Places a deploy script at /opt/deploy/deploy.sh (chowned player:player)
#   - Ensures nginx is running (deploy will fail but nginx serves stale content)
#
# 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 "Q004-prep: Preparing $DOMAIN for 'Not My Files'..."

# Ensure web root exists and is owned by root (the bug)
run_in_vm "mkdir -p /var/www/axiomworks && chown -R root:root /var/www/axiomworks"

# Create the deploy script as player:player (this is correct — player runs it)
run_in_vm "mkdir -p /opt/deploy"
run_in_vm "cat > /opt/deploy/deploy.sh <<'DEPLOY_SCRIPT'
#!/usr/bin/env bash
# deploy.sh — Axiom Works web deploy
# Copies build artifacts to /var/www/axiomworks/
set -e
SRC=\"\${1:-/home/player/build/dist}\"
rsync -av \"\$SRC/\" /var/www/axiomworks/
echo 'Deploy complete.'
DEPLOY_SCRIPT"
run_in_vm "chown player:player /opt/deploy/deploy.sh && chmod 755 /opt/deploy/deploy.sh"

# Ensure nginx is running (serves stale content with root-owned files)
run_in_vm "systemctl start nginx || true"

echo "Q004-prep: Done. /var/www/axiomworks is owned by root on $DOMAIN."
echo "         Player must: sudo chown -R player:player /var/www/axiomworks"
