#!/usr/bin/env bash
# Q001-prep.sh — Workstation baseline: SSH key missing
#
# Prepares the workstation VM for Q001 "Welcome Aboard".
# The player's SSH key was never added during provisioning.
#
# What this does:
#   - Ensures the player account exists
#   - Removes /home/player/.ssh/authorized_keys (key not provisioned)
#   - Leaves /var/log/auth.log with a "Permission denied (publickey)" entry
#
# Idempotent: safe to run multiple times.
# AGENT RULES: Never run against a live player session.

set -euo pipefail

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

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

SC_SSH_KEY="${SC_SSH_KEY:-${HOME}/.ssh/sc_host_key}"
SSH_USER="${SSH_USER:-opsbridge}"
SSH_OPTS="-o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -o BatchMode=yes -o ConnectTimeout=10 -o LogLevel=ERROR -i $SC_SSH_KEY"

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"
}

VM_IP="$(get_vm_ip "$DOMAIN")"
SSH="ssh $SSH_OPTS $SSH_USER@$VM_IP"

run_in_vm() {
    if [ "$DRY_RUN" = "true" ]; then
        echo "  [DRY-RUN in $DOMAIN] $*"
    else
        $SSH "sudo $*"
    fi
}

echo "Q001-prep: Preparing $DOMAIN for 'Welcome Aboard'..."

run_in_vm "bash -lc 'mkdir -p /home/player/.ssh; touch /var/log/auth.log; ts=\$(date +\"%b %d %H:%M:%S\"); echo \"\$ts ares sshd[1234]: Failed publickey for player from 10.42.0.1 port 22 ssh2\" >> /var/log/auth.log; rm -f /home/player/.ssh/authorized_keys; echo Q001-prep: authorized_keys removed'"

echo "Q001-prep: Done."
