#!/usr/bin/bash
# Deploy tuned inside VMs over SSH (sshd is the only approved access channel —
# see AGENTS.md "Access-channel policy: SSH only"). Formerly used the
# qemu guest-agent channel; converted to SSH now that all VMs have key + sudo.
set -uo pipefail

# Profile mapping: most VMs get throughput-performance, k8s/network-sensitive get network-latency
PROFILE="${1:-throughput-performance}"
REMOTE_SH="${REMOTE_SH:-$(cd "$(dirname "$0")/../../.." && pwd)/tests/remote.sh}"
VM_USER="${VM_USER:-localuser}"

deploy_vm() {
  local host="$1" vmid="$2" name="$3"
  # name is the Tailscale hostname (SSH target); vmid retained for reference.
  echo -n "  VMID $vmid ($name) on $host: "
  local result
  result=$(VM_IP="$name" VM_USER="$VM_USER" bash "$REMOTE_SH" vmroot \
    "DEBIAN_FRONTEND=noninteractive apt-get update -qq 2>/dev/null; \
     DEBIAN_FRONTEND=noninteractive apt-get install -y -qq tuned 2>/dev/null; \
     tuned-adm profile $PROFILE 2>/dev/null; \
     systemctl enable --now tuned 2>/dev/null; \
     tuned-adm active 2>/dev/null" </dev/null 2>&1)
  if echo "$result" | grep -q 'Current active'; then
    echo "$result" | grep -o 'Current active.*' | head -1
  elif echo "$result" | grep -qi 'permission denied\|no route\|timed out'; then
    echo "SSH FAILED (no key/no sudo) — run bootstrap-all.sh first"
  else
    echo "INSTALL FAILED (apt issue or no network)"
  fi
}

echo "============================================"
echo "  Deploying tuned ($PROFILE) to VMs via SSH"
echo "============================================"
echo ""

# tsys1 VMs
echo "--- pfv-tsys1 ---"
deploy_vm pfv-tsys1 100 pfv-bms
deploy_vm pfv-tsys1 101 tsys-ca
deploy_vm pfv-tsys1 102 pfv-k8s-cnode1
deploy_vm pfv-tsys1 104 tsys-librenms
deploy_vm pfv-tsys1 105 tsys-proxmox-datacenter
deploy_vm pfv-tsys1 108 tsys-ucs-01

# tsys3 VMs
echo "--- pfv-tsys3 ---"
deploy_vm pfv-tsys3 313 pfv-k8s-wnode-tsys3

# tsys6 VMs
echo "--- pfv-tsys6 ---"
deploy_vm pfv-tsys6 600 tsys-awx
deploy_vm pfv-tsys6 601 pfv-k8s-wnode-tsys6
deploy_vm pfv-tsys6 602 pfv-rr-middleware-02
deploy_vm pfv-tsys6 603 pfv-k8s-cnode3
deploy_vm pfv-tsys6 604 tsys-proxmox-mailgw-01

# tsys7 VMs
echo "--- pfv-tsys7 ---"
deploy_vm pfv-tsys7 701 pfv-k8s-wnode-tsys7
deploy_vm pfv-tsys7 702 hfnoc-uisp
deploy_vm pfv-tsys7 703 pfv-rr-middleware-01
deploy_vm pfv-tsys7 705 pfv-k8s-cnode2
deploy_vm pfv-tsys7 706 kali-rd
deploy_vm pfv-tsys7 707 tsys-siem
deploy_vm pfv-tsys7 708 kali-tsys
deploy_vm pfv-tsys7 709 tsys-voip
deploy_vm pfv-tsys7 711 tsys-proxmox-mailgw-02

# tsys9 VMs
echo "--- pfv-tsys9 ---"
deploy_vm pfv-tsys9 902 tsys-ucs-02
deploy_vm pfv-tsys9 905 pfv-k8s-wnode-tsys9

echo ""
echo "============================================"
echo "  Deployment complete."
echo "  NOT deployed (do-not-reboot VMs):"
echo "    ultix-streaming, ultix-offstage,"
echo "    pfv-netinfra-01, pfv-netinfra-02"
echo "============================================"
