#!/usr/bin/env bash
# Deploy Sankofa Services to pve2
# Sankofa/Phoenix/PanTel service layer on VLAN 160 (10.160.0.0/22)
# VMID Range: 7800-8999

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"

# Colors
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m'

log_info() { echo -e "${BLUE}[INFO]${NC} $1"; }
log_success() { echo -e "${GREEN}[✓]${NC} $1"; }
log_warn() { echo -e "${YELLOW}[WARN]${NC} $1"; }
log_error() { echo -e "${RED}[ERROR]${NC} $1"; }

# Configuration
PROXMOX_NODE="pve2"
PROXMOX_HOST="192.168.11.12"
# pve2 has: thin4, thin5, thin6 available (lvmthin)
PROXMOX_STORAGE="${PROXMOX_STORAGE:-thin4}"
CONTAINER_OS_TEMPLATE="local:vztmpl/ubuntu-22.04-standard_22.04-1_amd64.tar.zst"

# Sankofa Configuration
SANKOFA_VLAN="160"
SANKOFA_SUBNET="10.160.0.0/22"
SANKOFA_GATEWAY="10.160.0.1"

# VMID Allocation (Sankofa range: 7800-8999)
VMID_SANKOFA_API=7800
VMID_SANKOFA_PORTAL=7801
VMID_SANKOFA_KEYCLOAK=7802

# Service IPs (VLAN 160)
SANKOFA_API_IP="10.160.0.10"
SANKOFA_PORTAL_IP="10.160.0.11"
SANKOFA_KEYCLOAK_IP="10.160.0.12"

# Resource allocation
SANKOFA_API_MEMORY="4096"      # 4GB
SANKOFA_API_CORES="4"
SANKOFA_API_DISK="50"          # 50GB

SANKOFA_PORTAL_MEMORY="4096"   # 4GB
SANKOFA_PORTAL_CORES="4"
SANKOFA_PORTAL_DISK="50"       # 50GB

SANKOFA_KEYCLOAK_MEMORY="2048" # 2GB
SANKOFA_KEYCLOAK_CORES="2"
SANKOFA_KEYCLOAK_DISK="30"     # 30GB

# SSH function
ssh_pve2() {
    ssh -o StrictHostKeyChecking=no -o ConnectTimeout=5 root@"$PROXMOX_HOST" "$@"
}

# Check if container exists
container_exists() {
    local vmid=$1
    ssh_pve2 "pct list 2>/dev/null | grep -q '^\s*$vmid\s'" 2>/dev/null
}

# Create Sankofa container
create_sankofa_container() {
    local vmid=$1
    local hostname=$2
    local ip_address=$3
    local memory=$4
    local cores=$5
    local disk=$6
    local service_type=$7
    
    log_info "Creating Sankofa $service_type: $hostname (VMID: $vmid, IP: $ip_address)"
    
    if container_exists "$vmid"; then
        log_warn "Container $vmid ($hostname) already exists, skipping creation"
        return 0
    fi
    
    # Network configuration with VLAN 160
    # Note: Using DHCP for now (VLAN tagging may need bridge configuration)
    # For unprivileged containers, VLAN tagging might not work - use DHCP and configure at bridge level
    local network_config="bridge=vmbr0,name=eth0,ip=dhcp,type=veth"
    
    log_info "Creating container $vmid on $PROXMOX_NODE..."
    ssh_pve2 "pct create $vmid \
        $CONTAINER_OS_TEMPLATE \
        --storage $PROXMOX_STORAGE \
        --hostname $hostname \
        --memory $memory \
        --cores $cores \
        --rootfs $PROXMOX_STORAGE:$disk \
        --net0 '$network_config' \
        --unprivileged 1 \
        --swap 512 \
        --onboot 1 \
        --timezone America/Los_Angeles \
        --features nesting=1,keyctl=1" 2>&1
    
    if container_exists "$vmid"; then
        log_success "Container $vmid created successfully"
        
        # Start container
        log_info "Starting container $vmid..."
        ssh_pve2 "pct start $vmid" 2>&1 || true
        
        # Wait for container to be ready
        log_info "Waiting for container to be ready..."
        sleep 5
        
        # Basic setup
        log_info "Configuring container $vmid..."
        ssh_pve2 "pct exec $vmid -- bash -c 'export DEBIAN_FRONTEND=noninteractive; apt-get update -qq && apt-get install -y -qq curl wget git build-essential'" 2>&1 | grep -vE "(perl: warning|locale:)" || true
        
        log_success "Sankofa $service_type container $vmid ($hostname) deployed successfully"
        return 0
    else
        log_error "Failed to create container $vmid"
        return 1
    fi
}

# Main deployment
main() {
    echo ""
    log_info "========================================="
    log_info "Sankofa Deployment to pve2"
    log_info "========================================="
    echo ""
    log_info "Target Node: $PROXMOX_NODE ($PROXMOX_HOST)"
    log_info "VLAN: $SANKOFA_VLAN ($SANKOFA_SUBNET)"
    log_info "VMID Range: 7800-8999"
    echo ""
    
    # Check connectivity to pve2
    log_info "Checking connectivity to $PROXMOX_NODE..."
    if ! ssh_pve2 "pvecm status >/dev/null 2>&1"; then
        log_error "Cannot connect to $PROXMOX_NODE. Please check SSH access."
        exit 1
    fi
    log_success "Connected to $PROXMOX_NODE"
    echo ""
    
    # Check if containers already exist
    log_info "Checking existing Sankofa containers..."
    existing_containers=()
    if container_exists "$VMID_SANKOFA_API"; then
        existing_containers+=("$VMID_SANKOFA_API:sankofa-api-1")
        log_warn "Container $VMID_SANKOFA_API (sankofa-api-1) already exists"
    fi
    if container_exists "$VMID_SANKOFA_PORTAL"; then
        existing_containers+=("$VMID_SANKOFA_PORTAL:sankofa-portal-1")
        log_warn "Container $VMID_SANKOFA_PORTAL (sankofa-portal-1) already exists"
    fi
    if container_exists "$VMID_SANKOFA_KEYCLOAK"; then
        existing_containers+=("$VMID_SANKOFA_KEYCLOAK:sankofa-keycloak-1")
        log_warn "Container $VMID_SANKOFA_KEYCLOAK (sankofa-keycloak-1) already exists"
    fi
    
    if [[ ${#existing_containers[@]} -gt 0 ]]; then
        log_warn "Some Sankofa containers already exist:"
        for container in "${existing_containers[@]}"; do
            echo "  - $container"
        done
        echo ""
        read -p "Continue with deployment? (y/N): " -n 1 -r
        echo
        if [[ ! $REPLY =~ ^[Yy]$ ]]; then
            log_info "Deployment cancelled"
            exit 0
        fi
    fi
    echo ""
    
    # Deploy Sankofa API
    log_info "Deploying Sankofa API service..."
    create_sankofa_container \
        "$VMID_SANKOFA_API" \
        "sankofa-api-1" \
        "$SANKOFA_API_IP" \
        "$SANKOFA_API_MEMORY" \
        "$SANKOFA_API_CORES" \
        "$SANKOFA_API_DISK" \
        "API"
    echo ""
    
    # Deploy Sankofa Portal
    log_info "Deploying Sankofa Portal service..."
    create_sankofa_container \
        "$VMID_SANKOFA_PORTAL" \
        "sankofa-portal-1" \
        "$SANKOFA_PORTAL_IP" \
        "$SANKOFA_PORTAL_MEMORY" \
        "$SANKOFA_PORTAL_CORES" \
        "$SANKOFA_PORTAL_DISK" \
        "Portal"
    echo ""
    
    # Deploy Keycloak (optional)
    log_info "Deploying Keycloak identity service..."
    create_sankofa_container \
        "$VMID_SANKOFA_KEYCLOAK" \
        "sankofa-keycloak-1" \
        "$SANKOFA_KEYCLOAK_IP" \
        "$SANKOFA_KEYCLOAK_MEMORY" \
        "$SANKOFA_KEYCLOAK_CORES" \
        "$SANKOFA_KEYCLOAK_DISK" \
        "Keycloak"
    echo ""
    
    # Summary
    log_success "========================================="
    log_success "Sankofa Deployment Complete"
    log_success "========================================="
    echo ""
    log_info "Deployed containers on $PROXMOX_NODE:"
    echo "  - VMID $VMID_SANKOFA_API: sankofa-api-1 ($SANKOFA_API_IP)"
    echo "  - VMID $VMID_SANKOFA_PORTAL: sankofa-portal-1 ($SANKOFA_PORTAL_IP)"
    echo "  - VMID $VMID_SANKOFA_KEYCLOAK: sankofa-keycloak-1 ($SANKOFA_KEYCLOAK_IP)"
    echo ""
    log_info "Next steps:"
    echo "  1. Configure services in each container"
    echo "  2. Deploy application code from /home/intlc/projects/Sankofa"
    echo "  3. Configure networking and firewall rules"
    echo "  4. Set up Cloudflare tunnels for external access"
    echo ""
}

# Run main function
main "$@"

