#!/bin/bash
# Info: Polkadot Zombienet preparation script
# Author: Provisioning System
# Release: 1.0

echo "Preparing Polkadot Zombienet installation..."

# Load environment variables
[ -r "env-polkadot-zombienet" ] && . ./env-polkadot-zombienet

# Check if required tools are available
command -v curl >/dev/null 2>&1 || { echo "curl is required but not installed." >&2; exit 1; }

# Validate configuration
if [ -z "$ZOMBIENET_VERSION" ]; then
    echo "ZOMBIENET_VERSION must be set" >&2
    exit 1
fi

# Validate provider
case "${ZOMBIENET_PROVIDER:-native}" in
    "native"|"kubernetes"|"podman")
        echo "Provider: ${ZOMBIENET_PROVIDER}"
        ;;
    *)
        echo "Invalid provider: ${ZOMBIENET_PROVIDER}" >&2
        echo "Supported providers: native, kubernetes, podman" >&2
        exit 1
        ;;
esac

# Check provider-specific requirements
case "${ZOMBIENET_PROVIDER:-native}" in
    "kubernetes")
        if ! command -v kubectl >/dev/null 2>&1; then
            echo "kubectl is required for Kubernetes provider but not installed." >&2
            exit 1
        fi
        
        # Check if kubectl can connect to cluster
        if ! kubectl cluster-info >/dev/null 2>&1; then
            echo "Warning: kubectl cannot connect to Kubernetes cluster"
            echo "Make sure you have a valid kubeconfig and cluster access"
        else
            echo "✅ Kubernetes cluster access verified"
        fi
        ;;
    "podman")
        if ! command -v podman >/dev/null 2>&1; then
            echo "podman is required for Podman provider but not installed." >&2
            exit 1
        fi
        
        # Check podman version (Zombienet supports v2 or older)
        PODMAN_VERSION=$(podman --version | awk '{print $3}' | cut -d. -f1)
        if [ "$PODMAN_VERSION" -gt 2 ]; then
            echo "Warning: Zombienet currently supports Podman v2 or older"
            echo "You have Podman v$PODMAN_VERSION - you may need to apply patches"
        fi
        
        # Test podman functionality
        if ! podman info >/dev/null 2>&1; then
            echo "Warning: podman info failed - check podman configuration"
        else
            echo "✅ Podman is working"
        fi
        ;;
    "native")
        echo "Native provider selected - binaries will be downloaded automatically"
        ;;
esac

# Check available disk space
AVAILABLE_SPACE=$(df "${ZOMBIENET_WORK_PATH:-/var/lib/zombienet}" 2>/dev/null | awk 'NR==2 {print $4}' || echo "0")
REQUIRED_SPACE=5000000  # 5GB for binaries and network data
if [ "$AVAILABLE_SPACE" -ne "0" ] && [ "$AVAILABLE_SPACE" -lt "$REQUIRED_SPACE" ]; then
    echo "Warning: Low disk space for Zombienet"
    echo "Available: $(($AVAILABLE_SPACE / 1024))MB, Recommended: $(($REQUIRED_SPACE / 1024))MB"
fi

# Check memory requirements
if command -v free >/dev/null 2>&1; then
    FREE_MEMORY=$(free -m | awk '/^Mem:/{print $7}')
    MIN_MEMORY=4096  # Zombienet networks can be memory intensive
    
    if [ "$FREE_MEMORY" -lt "$MIN_MEMORY" ]; then
        echo "Warning: Low memory for Zombienet networks"
        echo "Available: ${FREE_MEMORY}MB, Recommended: ${MIN_MEMORY}MB"
        echo "Consider starting with simple networks or reducing node count"
    fi
fi

# Validate relay chain configuration
RELAYCHAIN_NODES=${ZOMBIENET_RELAYCHAIN_NODES:-2}
if [ "$RELAYCHAIN_NODES" -lt 2 ]; then
    echo "Error: At least 2 relay chain nodes are required" >&2
    exit 1
fi

# Check for common port conflicts
COMMON_PORTS=(30333 9944 9933 9615)
for port in "${COMMON_PORTS[@]}"; do
    if command -v netstat >/dev/null 2>&1; then
        if netstat -tuln | grep -q ":$port "; then
            echo "Warning: Port $port appears to be in use (common Polkadot port)"
        fi
    elif command -v ss >/dev/null 2>&1; then
        if ss -tuln | grep -q ":$port "; then
            echo "Warning: Port $port appears to be in use (common Polkadot port)"
        fi
    fi
done

# Check Docker/Podman for image availability (if not native)
if [ "${ZOMBIENET_PROVIDER:-native}" != "native" ]; then
    if [ "${ZOMBIENET_PROVIDER}" = "podman" ] && command -v podman >/dev/null 2>&1; then
        echo "Checking for required container images..."
        if ! podman image exists parity/polkadot:latest >/dev/null 2>&1; then
            echo "Info: parity/polkadot:latest image not found locally - will be pulled during network spawn"
        fi
    fi
fi

# Validate timeout settings
TIMEOUT=${ZOMBIENET_TIMEOUT:-1000}
if [ "$TIMEOUT" -lt 100 ]; then
    echo "Warning: Timeout seems very low ($TIMEOUT seconds)"
    echo "Network startup may fail with insufficient timeout"
fi

# Check for jq (useful for network info parsing)
if ! command -v jq >/dev/null 2>&1; then
    echo "Info: jq not found - JSON network info parsing will be limited"
fi

echo "Preparation completed successfully."
echo ""
echo "Zombienet configuration:"
echo "- Version: ${ZOMBIENET_VERSION}"
echo "- Provider: ${ZOMBIENET_PROVIDER:-native}"
echo "- Relay chain nodes: ${ZOMBIENET_RELAYCHAIN_NODES:-2}"
echo "- Parachains: ${ZOMBIENET_PARACHAINS_COUNT:-0}"
echo "- Timeout: ${ZOMBIENET_TIMEOUT:-1000}s"
echo "- Work path: ${ZOMBIENET_WORK_PATH:-/var/lib/zombienet}"

case "${ZOMBIENET_PROVIDER:-native}" in
    "kubernetes")
        echo "- Kubernetes namespace: ${ZOMBIENET_K8S_NAMESPACE:-zombienet}"
        ;;
    "podman")
        echo "- Podman monitoring: ${ZOMBIENET_PODMAN_MONITORING:-true}"
        ;;
    "native")
        echo "- Binaries path: ${ZOMBIENET_BINARIES_PATH:-/var/lib/zombienet/binaries}"
        ;;
esac