#!/usr/bin/env bash
# Deploy Services (Oracle Publisher, CCIP Monitor, Keeper, Financial Tokenization) on Proxmox VE LXC containers

set -euo pipefail

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

source "$PROJECT_ROOT/lib/common.sh"
source "$PROJECT_ROOT/lib/proxmox-api.sh"
source "$PROJECT_ROOT/lib/container-utils.sh" 2>/dev/null || true

# Load configuration
load_config
load_config "$PROJECT_ROOT/config/network.conf" || true

# Default values
DEPLOY_ORACLE="${DEPLOY_ORACLE:-true}"
DEPLOY_CCIP_MONITOR="${DEPLOY_CCIP_MONITOR:-true}"
DEPLOY_KEEPER="${DEPLOY_KEEPER:-true}"
DEPLOY_TOKENIZATION="${DEPLOY_TOKENIZATION:-true}"

# VMID ranges
VMID_SERVICES_START="${VMID_SERVICES_START:-3500}"

log_info "Starting services deployment..."

check_root
if ! command_exists pct; then
    error_exit "This script must be run on Proxmox host (pct command not found)"
fi

# Ensure OS template exists
ensure_os_template "${CONTAINER_OS_TEMPLATE:-local:vztmpl/ubuntu-22.04-standard_22.04-1_amd64.tar.zst}" || {
    error_exit "OS template not available. Please download it first."
}

# Function to create service container
create_service_container() {
    local service_type="$1"
    local vmid="$2"
    local hostname="$3"
    local ip_address="$4"
    local memory="${5:-2048}"
    local cores="${6:-2}"
    local disk="${7:-20}"
    
    log_info "Creating $service_type service: $hostname (VMID: $vmid, IP: $ip_address)"
    
    # Use DHCP for network configuration (matching successful containers 100-105)
    # Note: VLAN tagging removed - incompatible with unprivileged containers
    # Network isolation should be configured at bridge level or via firewall rules
    local network_config="bridge=${PROXMOX_BRIDGE:-vmbr0},name=eth0,ip=dhcp,type=veth"
    
    if pct list | grep -q "^\s*$vmid\s"; then
        log_warn "Container $vmid already exists, skipping creation"
    else
        log_info "Creating container $vmid..."
        pct create "$vmid" \
            "${CONTAINER_OS_TEMPLATE:-local:vztmpl/ubuntu-22.04-standard_22.04-1_amd64.tar.zst}" \
            --storage "${PROXMOX_STORAGE:-local-lvm}" \
            --hostname "$hostname" \
            --memory "$memory" \
            --cores "$cores" \
            --rootfs "${PROXMOX_STORAGE:-local-lvm}:${disk}" \
            --net0 "$network_config" \
            --unprivileged "${CONTAINER_UNPRIVILEGED:-1}" \
            --swap "${CONTAINER_SWAP:-512}" \
            --onboot "${CONTAINER_ONBOOT:-1}" \
            --timezone "${CONTAINER_TIMEZONE:-America/Los_Angeles}" \
            --features nesting=1,keyctl=1
        
        log_success "Container $vmid created"
    fi
    
    wait_for_container "$vmid"
    
    # Configure container
    log_info "Configuring container $vmid..."
    
    # Enable features
    pct set "$vmid" --features nesting=1,keyctl=1
    
    # Start container and wait for readiness (required for pct push and pct exec)
    if ! start_container_and_wait "$vmid"; then
        log_error "Failed to start container $vmid"
        return 1
    fi
    
    # Verify container is ready for file operations
    if ! verify_container_ready "$vmid"; then
        log_error "Container $vmid is not ready for file operations"
        return 1
    fi
    
    # Configure locale in container to suppress warnings
    pct exec "$vmid" -- bash -c "export LC_ALL=C; export LANG=C; echo 'export LC_ALL=C' >> /root/.bashrc; echo 'export LANG=C' >> /root/.bashrc; echo 'export LC_ALL=C' >> /etc/environment; echo 'export LANG=C' >> /etc/environment" 2>/dev/null || true
    
    local install_script="$PROJECT_ROOT/install/${service_type}-install.sh"
    if [[ ! -f "$install_script" ]]; then
        log_error "Install script not found: $install_script"
        return 1
    fi
    
    log_info "Installing $service_type in container $vmid..."
    # Push install script (filter locale warnings but preserve errors)
    pct push "$vmid" "$install_script" /tmp/install.sh 2>&1 | grep -vE "(perl: warning|locale: Cannot set|Setting locale failed)" || true
    if ! pct exec "$vmid" -- test -f /tmp/install.sh 2>/dev/null; then
        log_error "Failed to push install script to container $vmid"
        return 1
    fi
    # Execute install script (filter locale warnings but preserve other output)
    local install_output
    install_output=$(pct exec "$vmid" -- bash -c "export LC_ALL=C; export LANG=C; bash /tmp/install.sh" 2>&1)
    local install_exit=$?
    # Filter locale warnings but show everything else
    echo "$install_output" | grep -vE "(perl: warning|locale: Cannot set|Setting locale failed|Falling back to the standard locale)" || true
    if [[ $install_exit -ne 0 ]]; then
        log_error "Failed to execute install script in container $vmid"
        return 1
    fi
    
    log_success "$service_type service $hostname (VMID: $vmid) deployed successfully"
    echo "$vmid:$hostname:$ip_address"
}

# Deploy Oracle Publisher
if [[ "$DEPLOY_ORACLE" == "true" ]]; then
    vmid=$VMID_SERVICES_START
    hostname="oracle-publisher-1"
    ip_octet=50
    ip_address="${SERVICES_SUBNET:-10.3.1}.${ip_octet}"
    
    oracle_info=$(create_service_container \
        "oracle-publisher" \
        "$vmid" \
        "$hostname" \
        "$ip_address" \
        "${ORACLE_MEMORY:-2048}" \
        "${ORACLE_CORES:-2}" \
        "${ORACLE_DISK:-20}")
fi

# Deploy CCIP Monitor
if [[ "$DEPLOY_CCIP_MONITOR" == "true" ]]; then
    vmid=$((VMID_SERVICES_START + 1))
    hostname="ccip-monitor-1"
    ip_octet=51
    ip_address="${SERVICES_SUBNET:-10.3.1}.${ip_octet}"
    
    ccip_info=$(create_service_container \
        "ccip-monitor" \
        "$vmid" \
        "$hostname" \
        "$ip_address" \
        "${CCIP_MEMORY:-2048}" \
        "${CCIP_CORES:-2}" \
        "${CCIP_DISK:-20}")
fi

# Deploy Keeper
if [[ "$DEPLOY_KEEPER" == "true" ]]; then
    vmid=$((VMID_SERVICES_START + 2))
    hostname="keeper-1"
    ip_octet=52
    ip_address="${SERVICES_SUBNET:-10.3.1}.${ip_octet}"
    
    keeper_info=$(create_service_container \
        "keeper" \
        "$vmid" \
        "$hostname" \
        "$ip_address" \
        "${KEEPER_MEMORY:-2048}" \
        "${KEEPER_CORES:-2}" \
        "${KEEPER_DISK:-20}")
fi

# Deploy Financial Tokenization
if [[ "$DEPLOY_TOKENIZATION" == "true" ]]; then
    vmid=$((VMID_SERVICES_START + 3))
    hostname="tokenization-1"
    ip_octet=53
    ip_address="${SERVICES_SUBNET:-10.3.1}.${ip_octet}"
    
    token_info=$(create_service_container \
        "financial-tokenization" \
        "$vmid" \
        "$hostname" \
        "$ip_address" \
        "${TOKEN_MEMORY:-2048}" \
        "${TOKEN_CORES:-2}" \
        "${TOKEN_DISK:-20}")
fi

log_success "Services deployment completed!"

