#!/usr/bin/env bash
# Q003-prep.sh — hermes baseline: logrotate missing, nginx access log ballooning
#
# Prepares sc-web-server for Q003 "The Log That Ate the Disk".
# Assumes Q002 is already resolved (nginx is running, config is clean).
#
# What this does:
#   - Removes /etc/logrotate.d/nginx (log rotation not configured)
#   - Grows /var/log/nginx/access.log to ~80% disk pressure
#   - Disk usage should read >85% on /var so player sees the pressure
#
# 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 "Q003-prep: Preparing $DOMAIN for 'The Log That Ate the Disk'..."

# Remove logrotate config for nginx
run_in_vm "rm -f /etc/logrotate.d/nginx"

# Generate a large access log (~500MB of fake log entries, enough to fill a 6GB VM)
# Use truncate for speed rather than generating real content
run_in_vm "mkdir -p /var/log/nginx"
run_in_vm "truncate -s 500M /var/log/nginx/access.log"

# Write real-looking last few lines so tail shows something plausible
run_in_vm "echo '10.42.0.1 - - [\$(date +\"%d/%b/%Y:%H:%M:%S +0000\")] \"GET / HTTP/1.1\" 200 612 \"-\" \"Mozilla/5.0\"' >> /var/log/nginx/access.log"

echo "Q003-prep: Done. /var/log/nginx/access.log inflated on $DOMAIN."
echo "         Check disk pressure with: df -h (on the VM)"
