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

echo "Preparing Polkadot Bootnode installation..."

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

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

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

# Validate chain
case "${POLKADOT_CHAIN:-polkadot}" in
    "polkadot"|"kusama"|"westend")
        echo "Chain: ${POLKADOT_CHAIN}"
        ;;
    *)
        echo "Invalid chain: ${POLKADOT_CHAIN}" >&2
        exit 1
        ;;
esac

# Check bootnode port availability
BOOTNODE_PORTS=(
    "${POLKADOT_P2P_PORT:-30310}"
    "${POLKADOT_WS_PORT:-30311}"
    "${POLKADOT_WSS_PORT:-30312}"
)

for port in "${BOOTNODE_PORTS[@]}"; do
    if command -v netstat >/dev/null 2>&1; then
        if netstat -tuln | grep -q ":$port "; then
            echo "Warning: Bootnode port $port appears to be in use"
        fi
    elif command -v ss >/dev/null 2>&1; then
        if ss -tuln | grep -q ":$port "; then
            echo "Warning: Bootnode port $port appears to be in use"
        fi
    fi
done

# Validate port uniqueness
P2P_PORT=${POLKADOT_P2P_PORT:-30310}
WS_PORT=${POLKADOT_WS_PORT:-30311}
WSS_PORT=${POLKADOT_WSS_PORT:-30312}

if [ "$P2P_PORT" = "$WS_PORT" ] || [ "$P2P_PORT" = "$WSS_PORT" ] || [ "$WS_PORT" = "$WSS_PORT" ]; then
    echo "Error: Bootnode ports must be unique" >&2
    echo "P2P: $P2P_PORT, WS: $WS_PORT, WSS: $WSS_PORT" >&2
    exit 1
fi

# Validate WSS configuration for bootnode
if [ "${POLKADOT_WSS_ENABLED:-false}" = "true" ]; then
    if [ -z "$POLKADOT_WSS_DOMAIN" ]; then
        echo "Error: WSS enabled but domain not configured" >&2
        exit 1
    fi
    
    if [ "${POLKADOT_SSL_ENABLED:-false}" != "true" ]; then
        echo "Error: WSS requires SSL to be enabled" >&2
        exit 1
    fi
    
    if [ -z "$POLKADOT_SSL_CERT_FILE" ] || [ -z "$POLKADOT_SSL_KEY_FILE" ]; then
        echo "Error: SSL certificate files not configured" >&2
        exit 1
    fi
    
    echo "Bootnode WSS configuration validated for domain: $POLKADOT_WSS_DOMAIN"
fi

# Check if nginx is needed for WSS
if [ "${POLKADOT_WSS_ENABLED:-false}" = "true" ]; then
    if ! command -v nginx >/dev/null 2>&1; then
        echo "nginx will be installed for WSS proxy support"
    fi
fi

# Validate public address format if provided
if [ -n "$POLKADOT_PUBLIC_ADDR" ]; then
    if ! echo "$POLKADOT_PUBLIC_ADDR" | grep -qE '^/ip[46]/.*'; then
        echo "Warning: Public address format may be incorrect: $POLKADOT_PUBLIC_ADDR"
        echo "Expected format: /ip4/YOUR_IP/tcp/PORT or /ip6/YOUR_IP/tcp/PORT"
    fi
fi

# Check available disk space (bootnode needs minimal space)
AVAILABLE_SPACE=$(df "${POLKADOT_BASE_PATH:-/var/lib/polkadot-bootnode/data}" 2>/dev/null | awk 'NR==2 {print $4}' || echo "0")
REQUIRED_SPACE=1000000  # 1GB should be enough for bootnode
if [ "$AVAILABLE_SPACE" -ne "0" ] && [ "$AVAILABLE_SPACE" -lt "$REQUIRED_SPACE" ]; then
    echo "Warning: Low disk space for bootnode"
    echo "Available: $(($AVAILABLE_SPACE / 1024))MB, Recommended: $(($REQUIRED_SPACE / 1024))MB"
fi

# Check memory requirements (bootnode is lightweight)
if command -v free >/dev/null 2>&1; then
    FREE_MEMORY=$(free -m | awk '/^Mem:/{print $7}')
    MIN_MEMORY=512  # Bootnode needs minimal memory
    
    if [ "$FREE_MEMORY" -lt "$MIN_MEMORY" ]; then
        echo "Warning: Very low memory for bootnode"
        echo "Available: ${FREE_MEMORY}MB, Minimum: ${MIN_MEMORY}MB"
    fi
fi

echo "Preparation completed successfully."
echo ""
echo "Bootnode configuration:"
echo "- Chain: ${POLKADOT_CHAIN:-polkadot}"
echo "- P2P port: ${POLKADOT_P2P_PORT:-30310}"
echo "- WS port: ${POLKADOT_WS_PORT:-30311}"
echo "- WSS port: ${POLKADOT_WSS_PORT:-30312}"
echo "- WSS enabled: ${POLKADOT_WSS_ENABLED:-false}"
echo "- Public address: ${POLKADOT_PUBLIC_ADDR:-auto-detect}"
echo "- Data path: ${POLKADOT_BASE_PATH:-/var/lib/polkadot-bootnode/data}"