#!/usr/bin/env bash
# Deploy Hyperledger Services (Firefly, Cacti, Fabric, Indy) 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_FIREFLY="${DEPLOY_FIREFLY:-true}"
DEPLOY_CACTI="${DEPLOY_CACTI:-true}"
DEPLOY_FABRIC="${DEPLOY_FABRIC:-false}"
DEPLOY_INDY="${DEPLOY_INDY:-false}"

# VMID ranges
VMID_FIREFLY_START="${VMID_FIREFLY_START:-150}"
VMID_CACTI_START="${VMID_CACTI_START:-151}"
VMID_FABRIC_START="${VMID_FABRIC_START:-152}"
VMID_INDY_START="${VMID_INDY_START:-153}"

log_info "Starting Hyperledger services deployment..."

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

check_root

# 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 and configure Hyperledger service
create_hyperledger_service() {
    local service_type="$1"  # firefly, cacti, fabric, indy
    local vmid="$2"
    local hostname="$3"
    local ip_address="$4"
    local memory="${5:-4096}"
    local cores="${6:-2}"
    local disk="${7:-50}"
    
    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"
    
    # Create container
    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 to be ready
    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
    
    # Install service
    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
    
    # 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
    
    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=$?
    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"
    
    # Return container info
    echo "$vmid:$hostname:$ip_address"
}

# Deploy Firefly
if [[ "$DEPLOY_FIREFLY" == "true" ]]; then
    log_info "Deploying Firefly service..."
    vmid=$VMID_FIREFLY_START
    hostname="firefly-1"
    ip_octet=60
    ip_address="${SERVICES_SUBNET:-10.3.1}.${ip_octet}"
    
    firefly_info=$(create_hyperledger_service \
        "firefly" \
        "$vmid" \
        "$hostname" \
        "$ip_address" \
        "${FIREFLY_MEMORY:-4096}" \
        "${FIREFLY_CORES:-2}" \
        "${FIREFLY_DISK:-50}")
    
    log_success "Deployed Firefly service"
fi

# Deploy Cacti
if [[ "$DEPLOY_CACTI" == "true" ]]; then
    log_info "Deploying Cacti service..."
    vmid=$VMID_CACTI_START
    hostname="cacti-1"
    ip_octet=61
    ip_address="${SERVICES_SUBNET:-10.3.1}.${ip_octet}"
    
    cacti_info=$(create_hyperledger_service \
        "cacti" \
        "$vmid" \
        "$hostname" \
        "$ip_address" \
        "${CACTI_MEMORY:-4096}" \
        "${CACTI_CORES:-2}" \
        "${CACTI_DISK:-50}")
    
    log_success "Deployed Cacti service"
fi

# Deploy Fabric
if [[ "$DEPLOY_FABRIC" == "true" ]]; then
    log_info "Deploying Fabric service..."
    vmid=$VMID_FABRIC_START
    hostname="fabric-1"
    ip_octet=62
    ip_address="${SERVICES_SUBNET:-10.3.1}.${ip_octet}"
    
    fabric_info=$(create_hyperledger_service \
        "fabric" \
        "$vmid" \
        "$hostname" \
        "$ip_address" \
        "${FABRIC_MEMORY:-8192}" \
        "${FABRIC_CORES:-4}" \
        "${FABRIC_DISK:-100}")
    
    log_success "Deployed Fabric service"
fi

# Deploy Indy
if [[ "$DEPLOY_INDY" == "true" ]]; then
    log_info "Deploying Indy service..."
    vmid=$VMID_INDY_START
    hostname="indy-1"
    ip_octet=63
    ip_address="${SERVICES_SUBNET:-10.3.1}.${ip_octet}"
    
    indy_info=$(create_hyperledger_service \
        "indy" \
        "$vmid" \
        "$hostname" \
        "$ip_address" \
        "${INDY_MEMORY:-8192}" \
        "${INDY_CORES:-4}" \
        "${INDY_DISK:-100}")
    
    log_success "Deployed Indy service"
fi

# Update inventory
log_info "Updating deployment inventory..."
INVENTORY_FILE="$PROJECT_ROOT/config/inventory.conf"
if [[ -f "$INVENTORY_FILE" ]]; then
    cat >> "$INVENTORY_FILE" <<EOF

# Hyperledger Services
EOF
    
    if [[ -n "${firefly_info:-}" ]]; then
        IFS=':' read -r vmid hostname ip <<< "$firefly_info"
        echo "FIREFLY_${hostname//-/}_VMID=$vmid" >> "$INVENTORY_FILE"
        echo "FIREFLY_${hostname//-/}_IP=$ip" >> "$INVENTORY_FILE"
    fi
    
    if [[ -n "${cacti_info:-}" ]]; then
        IFS=':' read -r vmid hostname ip <<< "$cacti_info"
        echo "CACTI_${hostname//-/}_VMID=$vmid" >> "$INVENTORY_FILE"
        echo "CACTI_${hostname//-/}_IP=$ip" >> "$INVENTORY_FILE"
    fi
    
    if [[ -n "${fabric_info:-}" ]]; then
        IFS=':' read -r vmid hostname ip <<< "$fabric_info"
        echo "FABRIC_${hostname//-/}_VMID=$vmid" >> "$INVENTORY_FILE"
        echo "FABRIC_${hostname//-/}_IP=$ip" >> "$INVENTORY_FILE"
    fi
    
    if [[ -n "${indy_info:-}" ]]; then
        IFS=':' read -r vmid hostname ip <<< "$indy_info"
        echo "INDY_${hostname//-/}_VMID=$vmid" >> "$INVENTORY_FILE"
        echo "INDY_${hostname//-/}_IP=$ip" >> "$INVENTORY_FILE"
    fi
fi

log_success "Hyperledger services deployment completed!"

