#!/usr/bin/bash
# phase1-access-audit.sh — Try SSH to every Tailscale Linux system
# Reports: reachable as localuser, reachable as root, or needs key
set -uo pipefail

SSH_OPTS=(-o BatchMode=yes -o StrictHostKeyChecking=accept-new -o ConnectTimeout=8)

# All Linux systems from tailscale status (excluding Windows, offline, switches)
SYSTEMS=(
  # Proxmox hosts (try root first)
  pfv-tsys1 pfv-tsys3 pfv-tsys4 pfv-tsys5 pfv-tsys6 pfv-tsys7 pfv-tsys9
  # K8s nodes
  pfv-k8s-cnode1 pfv-k8s-cnode2 pfv-k8s-cnode3
  pfv-k8s-wnode-tsys3 pfv-k8s-wnode-tsys5 pfv-k8s-wnode-tsys6
  pfv-k8s-wnode-tsys7 pfv-k8s-wnode-tsys9
  # Netinfra
  pfv-netinfra-01 pfv-netinfra-02
  # Production VMs
  pfv-bms devbox-cloudron hfnoc-uisp kali-rd kali-tsys
  pfv-rr-middleware-01 pfv-rr-middleware-02
  # Ultix (do not modify, just probe)
  ultix-streaming ultix-offstage
  # Preprod
  preprod-awx preprod-ca preprod-cloudron preprod-hfnoc-uisp
  preprod-librenms preprod-proxmox-datacenter preprod-proxmox-mailgw
  preprod-rancherplatform preprod-siem preprod-voip
  # Sectestbed
  sectestbed-awx sectestbed-ca sectestbed-cloudron sectestbed-hfnoc-uisp
  sectestbed-k8s-cnode sectestbed-k8s-wnode sectestbed-librenms
  sectestbed-netinfra sectestbed-proxmox-datacenter sectestbed-proxmox-mailgw
  sectestbed-proxmox-pbs sectestbed-proxmox-pve sectestbed-rancherplatform
  sectestbed-sandbox sectestbed-siem sectestbed-voip
  # Other Linux
  netbird pfv-jetson-nano-1 pfv-proxmox-backup-server pfvsvrpi
  subopi-dev-3 stlpc-artroom stlpc-garage
)

echo "system	localuser	root	status"
echo "------	---------	----	------"

for sys in "${SYSTEMS[@]}"; do
  lu_ok="no"
  root_ok="no"
  ts_ip=""

  # Try localuser first
  if ssh "${SSH_OPTS[@]}" "localuser@${sys}" 'echo ok' 2>/dev/null | grep -q ok; then
    lu_ok="yes"
    ts_ip=$(ssh "${SSH_OPTS[@]}" "localuser@${sys}" 'tailscale ip -4 2>/dev/null || echo "?"' 2>/dev/null)
  fi

  # Try root
  if ssh "${SSH_OPTS[@]}" "root@${sys}" 'echo ok' 2>/dev/null | grep -q ok; then
    root_ok="yes"
    [ -z "$ts_ip" ] && ts_ip=$(ssh "${SSH_OPTS[@]}" "root@${sys}" 'tailscale ip -4 2>/dev/null || echo "?"' 2>/dev/null)
  fi

  # Determine status
  if [ "$lu_ok" = "yes" ] && [ "$root_ok" = "yes" ]; then
    status="OK (both)"
  elif [ "$lu_ok" = "yes" ]; then
    status="OK (localuser only)"
  elif [ "$root_ok" = "yes" ]; then
    status="OK (root only)"
  else
    status="NO ACCESS"
  fi

  echo "$sys	$lu_ok	$root_ok	$status	${ts_ip:-}"
done
