#!/bin/sh
# Pull docker-compose + .env uit Proxmox LXC's via SSH (draait op NAS).
# Vereist: Docker, Proxmox root-wachtwoord in PROXMOX_PASSWORD
set -e
ROOT="$(cd "$(dirname "$0")/.." && pwd)"
PW="${PROXMOX_PASSWORD:-WaQTUw2t}"
SSH_RUN() {
  docker run --rm alpine sh -c "
    apk add --no-cache openssh-client sshpass >/dev/null 2>&1
    sshpass -p '$PW' ssh -o StrictHostKeyChecking=no root@\$1 \"\$2\"
  " -- "$1" "$2"
}

pull_ct() {
  host="$1"
  node="$2"
  vmid="$3"
  name="$4"
  ip="$5"
  appdir="$ROOT/apps/$name"
  mkdir -p "$appdir/config"

  echo "  → $name (CT $vmid @ $node, $ip)"

  # docker-compose bestanden vinden en kopiëren
  SSH_RUN "$host" "pct exec $vmid -- sh -c '
    find / -maxdepth 6 \( -name docker-compose.yml -o -name docker-compose.yaml -o -name compose.yml \) 2>/dev/null | grep -v proc | head -30
  '" > /tmp/lxc-compose-list.$$ 2>/dev/null || true

  idx=0
  while IFS= read -r fpath; do
    [ -z "$fpath" ] && continue
    idx=$((idx + 1))
    safe=$(echo "$fpath" | tr '/ ' '__')
    SSH_RUN "$host" "pct exec $vmid -- cat '$fpath'" > "$appdir/config/compose-${idx}-${safe}" 2>/dev/null || true
    dir=$(dirname "$fpath")
    SSH_RUN "$host" "pct exec $vmid -- sh -c 'for e in $dir/.env $dir/.env.local; do [ -f \"\$e\" ] && echo === \$e === && cat \"\$e\"; done'" \
      > "$appdir/config/env-${idx}-${safe}" 2>/dev/null || true
  done < /tmp/lxc-compose-list.$$
  rm -f /tmp/lxc-compose-list.$$

  # meta
  cat > "$appdir/proxmox.meta.yaml" <<META
# Auto-generated — Proxmox LXC
host: $node
proxmox_ip: $host
vmid: $vmid
hostname: $name
ip: $ip
META
}

echo "Pull LXC configs → $ROOT/apps/"

# draaiende containers (feb 2026)
pull_ct 192.168.1.216 pve 104 vaultwarden 192.168.1.5
pull_ct 192.168.1.216 pve 105 linkwarden 192.168.1.142
pull_ct 192.168.1.216 pve 107 pve-scripts-local 192.168.1.23
pull_ct 192.168.1.216 pve 117 proxy 192.168.1.165
pull_ct 192.168.1.216 pve 118 paymenter 192.168.1.45
pull_ct 192.168.1.216 pve 119 nodecast-tv 192.168.1.99

pull_ct 192.168.1.56 proxmox 107 virtualmin 192.168.5.24
pull_ct 192.168.1.56 proxmox 109 nginx-proxy-manager 192.168.1.173
pull_ct 192.168.1.56 proxmox 111 pegaprox 192.168.1.249

echo "Klaar."
