#!/bin/bash
# Verify Proxmox node is ready for LXC container deployment
# Usage: ./verify-node-ready.sh [node-name]

set -e

NODE="${1:-r630-01}"

echo "========================================="
echo "Verifying Node: $NODE"
echo "========================================="
echo ""

# Check if pvesh is available
if ! command -v pvesh >/dev/null 2>&1; then
  echo "❌ Error: pvesh command not found"
  echo "This script must be run on a Proxmox host or with API access configured"
  exit 1
fi

# Check node exists and is online
echo "1. Checking node status..."
if ! pvesh get /nodes/$NODE/status >/dev/null 2>&1; then
  echo "❌ Node '$NODE' not found or not accessible"
  echo ""
  echo "Available nodes:"
  pvesh get /nodes --output-format json 2>/dev/null | \
    grep -o '"node":"[^"]*"' | cut -d'"' -f4 | sort | sed 's/^/   - /'
  exit 1
fi

NODE_STATUS=$(pvesh get /nodes/$NODE/status --output-format json 2>/dev/null)
NODE_STATUS_TEXT=$(echo "$NODE_STATUS" | grep -o '"status":"[^"]*"' | cut -d'"' -f4)

if [ "$NODE_STATUS_TEXT" != "online" ]; then
  echo "❌ Node is not online (status: $NODE_STATUS_TEXT)"
  exit 1
fi

echo "✅ Node is online"
echo ""

# Check storage
echo "2. Checking storage..."
STORAGE_JSON=$(pvesh get /nodes/$NODE/storage --output-format json 2>/dev/null)
STORAGE_LIST=$(echo "$STORAGE_JSON" | grep -o '"storage":"[^"]*"' | cut -d'"' -f4 | sort)

if echo "$STORAGE_LIST" | grep -q "local-lvm\|local"; then
  echo "✅ Storage available:"
  echo "$STORAGE_LIST" | sed 's/^/   - /'
else
  echo "❌ No suitable storage found (need local-lvm or local)"
  exit 1
fi
echo ""

# Check for LXC templates
echo "3. Checking LXC templates..."
TEMPLATES=$(pvesh get /nodes/$NODE/storage --output-format json 2>/dev/null | \
  grep -o '"content":"[^"]*vztmpl[^"]*"' | \
  sed 's/.*"content":"\([^"]*\)".*/\1/' | sort -u || echo "")

if [ -z "$TEMPLATES" ]; then
  echo "⚠️  No LXC templates found"
  echo ""
  echo "Please download templates in Proxmox UI:"
  echo "  1. Datacenter > Storage > local (or local-lvm)"
  echo "  2. Click 'Templates' tab"
  echo "  3. Click 'Download Templates'"
  echo "  4. Select and download: ubuntu-22.04-standard (or similar)"
  echo ""
else
  echo "✅ Available templates:"
  echo "$TEMPLATES" | sed 's/^/   - /' | head -10
  if echo "$TEMPLATES" | grep -qi "ubuntu.*22.04"; then
    echo ""
    echo "✅ Ubuntu 22.04 template available (recommended)"
  else
    echo ""
    echo "⚠️  Ubuntu 22.04 template not found, but other templates available"
  fi
fi
echo ""

# Check network
echo "4. Checking network configuration..."
BRIDGES=$(pvesh get /nodes/$NODE/network --output-format json 2>/dev/null | \
  grep -o '"iface":"vmbr[^"]*"' | cut -d'"' -f4 | sort || echo "")

if echo "$BRIDGES" | grep -q "vmbr0"; then
  echo "✅ Network bridge vmbr0 found"
  echo "$BRIDGES" | sed 's/^/   - /'
else
  echo "⚠️  vmbr0 not found, but other bridges available:"
  echo "$BRIDGES" | sed 's/^/   - /'
  echo "Note: Scripts assume vmbr0, adjust if needed"
fi
echo ""

# Check available resources
echo "5. Checking available resources..."
NODE_RESOURCES=$(pvesh get /nodes/$NODE/status --output-format json 2>/dev/null)
MAXMEM=$(echo "$NODE_RESOURCES" | grep -o '"maxmem":[0-9]*' | cut -d':' -f2)
MAXDISK=$(echo "$NODE_RESOURCES" | grep -o '"maxdisk":[0-9]*' | cut -d':' -f2)
MEM=$(echo "$NODE_RESOURCES" | grep -o '"mem":[0-9]*' | cut -d':' -f2)
DISK=$(echo "$NODE_RESOURCES" | grep -o '"disk":[0-9]*' | cut -d':' -f2)

if [ -n "$MAXMEM" ] && [ -n "$MEM" ]; then
  MEM_FREE=$((MAXMEM - MEM))
  MEM_FREE_GB=$((MEM_FREE / 1024 / 1024))
  echo "   Memory: ${MEM_FREE_GB}GB free"
  
  # Required: 2GB + 2GB + 2GB = 6GB for 3 containers
  if [ $MEM_FREE_GB -lt 6 ]; then
    echo "⚠️  Warning: Less than 6GB free (recommended: 6GB+ for 3 containers)"
  else
    echo "✅ Sufficient memory available"
  fi
fi

if [ -n "$MAXDISK" ] && [ -n "$DISK" ]; then
  DISK_FREE=$((MAXDISK - DISK))
  DISK_FREE_GB=$((DISK_FREE / 1024 / 1024 / 1024))
  echo "   Disk: ${DISK_FREE_GB}GB free"
  
  # Required: 10GB + 20GB + 20GB = 50GB for 3 containers
  if [ $DISK_FREE_GB -lt 50 ]; then
    echo "⚠️  Warning: Less than 50GB free (recommended: 50GB+ for 3 containers)"
  else
    echo "✅ Sufficient disk space available"
  fi
fi
echo ""

# Check existing containers on target VMIDs
echo "6. Checking VMID availability..."
declare -a REQUIRED_VMIDS=(106 107 108)
CONFLICTS=0

for VMID in "${REQUIRED_VMIDS[@]}"; do
  if pvesh get /nodes/$NODE/qemu/$VMID/config >/dev/null 2>&1 || \
     pvesh get /nodes/$NODE/lxc/$VMID/config >/dev/null 2>&1; then
    echo "⚠️  VMID $VMID already exists on $NODE"
    CONFLICTS=$((CONFLICTS + 1))
  else
    echo "✅ VMID $VMID is available"
  fi
done

if [ $CONFLICTS -gt 0 ]; then
  echo ""
  echo "⚠️  Warning: $CONFLICTS VMID(s) already exist"
  echo "   Deployment script will skip existing VMIDs"
fi
echo ""

# Summary
echo "========================================="
echo "Verification Summary"
echo "========================================="
echo "Node: $NODE"
echo "Status: ✅ Ready for container deployment"
echo ""
echo "Next steps:"
echo "1. Run deployment script: ./deploy-supporting-services.sh $NODE"
echo "2. Or manually create containers using pct create command"
echo "3. See DEPLOYMENT.md for detailed configuration steps"
