#!/bin/bash
# deploy-keys.sh — deploy workstation SSH pubkeys to hubris + all LXCs
#
# Run from hubris (PVE host) as root.
# Reads keys from /opt/homelab-context/ssh/authorized_keys/*.pub
# and appends them to /root/.ssh/authorized_keys in each running LXC,
# and to /etc/pve/priv/authorized_keys on hubris.
#
# Idempotent — skips keys already present.

set -euo pipefail

KEYS_DIR="/opt/homelab-context/ssh/authorized_keys"

if ! [ -d "$KEYS_DIR" ]; then
  echo "ERROR: $KEYS_DIR not found. Is homelab context synced?"
  exit 1
fi

# Collect all pubkeys into a single variable, one per line
ALL_KEYS=""
for f in "$KEYS_DIR"/*.pub; do
  [ -f "$f" ] || continue
  key=$(cat "$f" | head -1)
  ALL_KEYS="${ALL_KEYS}${key}
"
done

if [ -z "$ALL_KEYS" ]; then
  echo "ERROR: no .pub files found in $KEYS_DIR"
  exit 1
fi

echo "= Deploying SSH keys to hubris ="
AUTH_FILE="/etc/pve/priv/authorized_keys"
touch "$AUTH_FILE"
added=0
while IFS= read -r key; do
  [ -z "$key" ] && continue
  if ! grep -qF "$key" "$AUTH_FILE" 2>/dev/null; then
    echo "  + Adding key to hubris: ${key:0:40}..."
    echo "$key" >> "$AUTH_FILE"
    added=$((added + 1))
  fi
done <<< "$ALL_KEYS"
echo "  hubris: $added key(s) added"

# Deploy to LXCs
echo ""
echo "= Deploying SSH keys to LXCs ="

# pct list output: VMID Status Lock Name (Lock may be empty)
# Use awk to grab VMID, Status, and Name (last field)
pct list | tail -n +2 | while read -r line; do
  vmid=$(echo "$line" | awk '{print $1}')
  status=$(echo "$line" | awk '{print $2}')
  name=$(echo "$line" | awk '{print $NF}')
  # Skip header if any
  [ "$vmid" = "VMID" ] && continue
  [ -z "$vmid" ] && continue
  if [ "$status" != "running" ]; then
    echo "  SKIP $name ($vmid): status=$status"
    continue
  fi

  echo "  -> $name ($vmid)"

  # Ensure .ssh directory exists
  pct exec "$vmid" -- mkdir -p /root/.ssh 2>/dev/null

  # For each key, check if already present, append if not
  while IFS= read -r key; do
    [ -z "$key" ] && continue
    if ! pct exec "$vmid" -- grep -qF "$key" /root/.ssh/authorized_keys 2>/dev/null; then
      echo "     + ${key:0:40}..."
      # Use tee to append (pct exec preserves stdin)
      echo "$key" | pct exec "$vmid" -- tee -a /root/.ssh/authorized_keys >/dev/null 2>&1
    fi
  done <<< "$ALL_KEYS"

  # Fix permissions
  pct exec "$vmid" -- chmod 600 /root/.ssh/authorized_keys 2>/dev/null || true
  pct exec "$vmid" -- chmod 700 /root/.ssh 2>/dev/null || true

  echo "  <- $name done"
done

echo ""
echo "=== Deploy complete ==="
echo "Keys deployed. Test from any workstation with:"
echo "  ssh root@<lxc-ip>"