#!/bin/bash
# Deploy Supporting Services (Redis, Web3Signer, Vault) as LXC containers
# Usage: ./deploy-supporting-services.sh [node-name]

set -e

NODE="${1:-r630-01}"  # Default to r630-01 if not specified

# VMID and IP allocations
declare -A SERVICES=(
  ["106"]="192.168.11.110:redis-rpc-translator:redis"
  ["107"]="192.168.11.111:web3signer-rpc-translator:web3signer"
  ["108"]="192.168.11.112:vault-rpc-translator:vault"
)

# Container specifications
declare -A CONTAINER_SPECS=(
  ["redis"]="2:512:10"      # cores:memory(MB):disk(GB)
  ["web3signer"]="2:2048:20"
  ["vault"]="2:2048:20"
)

echo "========================================="
echo "Deploying Supporting Services to $NODE"
echo "========================================="
echo ""

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

# Check available templates
echo "Checking available LXC templates on $NODE..."
TEMPLATES=$(pvesh get /nodes/$NODE/storage --output-format json 2>/dev/null | grep -o '"content":"[^"]*"' | grep -o "vztmpl\|iso" | head -1 || echo "")
if [ -z "$TEMPLATES" ]; then
  echo "⚠️  Warning: Could not determine available templates"
  echo "Please verify templates are available on $NODE"
fi

echo "✅ Node $NODE is accessible"
echo ""

# Function to create container
create_container() {
  local VMID=$1
  local IP=$2
  local HOSTNAME=$3
  local SERVICE=$4
  
  echo "Creating $SERVICE container (VMID $VMID, IP $IP)..."
  
  # Check if VMID already exists
  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, skipping..."
    return 1
  fi
  
  # Get container specs
  IFS=':' read -r CORES MEMORY DISK <<< "${CONTAINER_SPECS[$SERVICE]}"
  
  # Determine template (use ubuntu-22.04-standard if available, else generic)
  TEMPLATE="local:vztmpl/ubuntu-22.04-standard_22.04-1_amd64.tar.zst"
  
  # Try to find available template
  AVAILABLE_TEMPLATES=$(pvesh get /nodes/$NODE/storage --output-format json 2>/dev/null | \
    grep -o '"content":"[^"]*vztmpl[^"]*"' | head -5 || echo "")
  
  if [ -z "$AVAILABLE_TEMPLATES" ]; then
    echo "❌ Error: No LXC templates found on $NODE"
    echo "Please ensure templates are downloaded in Proxmox UI:"
    echo "  Datacenter > Storage > local > Templates > Download Templates"
    exit 1
  fi
  
  # Use first available Ubuntu template (prefer 22.04, fallback to others)
  TEMPLATE=$(echo "$AVAILABLE_TEMPLATES" | grep -o "ubuntu-22.04[^,]*" | head -1 || \
             echo "$AVAILABLE_TEMPLATES" | grep -o "ubuntu[^,]*" | head -1 || \
             echo "$AVAILABLE_TEMPLATES" | head -1)
  
  if [ -z "$TEMPLATE" ]; then
    TEMPLATE="local:vztmpl/ubuntu-22.04-standard_22.04-1_amd64.tar.zst"
  fi
  
  echo "  Template: $TEMPLATE"
  echo "  Specs: ${CORES} cores, ${MEMORY}MB RAM, ${DISK}GB disk"
  
  # Create container
  pct create $VMID "$TEMPLATE" \
    --hostname "$HOSTNAME" \
    --cores $CORES \
    --memory $MEMORY \
    --swap $MEMORY \
    --storage local-lvm \
    --rootfs local-lvm:${DISK} \
    --net0 name=eth0,bridge=vmbr0,ip=$IP/24,gw=192.168.11.1 \
    --onboot 1 \
    --start 0 \
    --unprivileged 0 \
    --features nesting=1,keyctl=1 || {
    echo "❌ Failed to create container $VMID"
    return 1
  }
  
  echo "✅ Container $VMID ($HOSTNAME) created successfully"
  echo ""
}

# Create all containers
for VMID in "${!SERVICES[@]}"; do
  IFS=':' read -r IP HOSTNAME SERVICE <<< "${SERVICES[$VMID]}"
  create_container "$VMID" "$IP" "$HOSTNAME" "$SERVICE"
done

echo "========================================="
echo "✅ Container Creation Complete"
echo "========================================="
echo ""
echo "Next steps:"
echo "1. Start containers:"
for VMID in "${!SERVICES[@]}"; do
  IFS=':' read -r IP HOSTNAME SERVICE <<< "${SERVICES[$VMID]}"
  echo "   pct start $VMID  # $HOSTNAME"
done
echo ""
echo "2. Configure each container (see DEPLOYMENT.md for details)"
echo "3. Verify connectivity from translator VMIDs (2400-2402)"
