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

echo "Preparing Polkadot Node installation..."

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

# 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 node type
case "${POLKADOT_NODE_TYPE:-full}" in
    "full"|"light"|"validator")
        echo "Node type: ${POLKADOT_NODE_TYPE}"
        ;;
    *)
        echo "Invalid node type: ${POLKADOT_NODE_TYPE}" >&2
        exit 1
        ;;
esac

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

# Check available disk space based on node type and pruning
case "${POLKADOT_NODE_TYPE:-full}" in
    "light")
        REQUIRED_SPACE=1000000  # 1GB
        ;;
    "full")
        if [ "${POLKADOT_ARCHIVE_MODE:-false}" = "true" ]; then
            REQUIRED_SPACE=500000000  # 500GB for archive
        else
            REQUIRED_SPACE=50000000   # 50GB for pruned
        fi
        ;;
    "validator")
        REQUIRED_SPACE=100000000  # 100GB for validator
        ;;
esac

AVAILABLE_SPACE=$(df "${POLKADOT_BASE_PATH:-/var/lib/polkadot/data}" 2>/dev/null | awk 'NR==2 {print $4}' || echo "0")
if [ "$AVAILABLE_SPACE" -ne "0" ] && [ "$AVAILABLE_SPACE" -lt "$REQUIRED_SPACE" ]; then
    echo "Warning: Insufficient disk space for ${POLKADOT_NODE_TYPE} node"
    echo "Available: $(($AVAILABLE_SPACE / 1024))MB, Recommended: $(($REQUIRED_SPACE / 1024))MB"
fi

# Check port availability
PORTS=(
    "${POLKADOT_RPC_PORT:-9944}"
    "${POLKADOT_WS_PORT:-9944}"
    "${POLKADOT_HTTP_PORT:-9933}"
    "30333"  # P2P port
)

for port in "${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"
        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"
        fi
    fi
done

# Validate pruning configuration
if [ "${POLKADOT_ARCHIVE_MODE:-false}" = "true" ] && [ "${POLKADOT_PRUNING_ENABLED:-true}" = "true" ]; then
    echo "Error: Cannot enable both archive mode and pruning" >&2
    exit 1
fi

# Validate WSS configuration
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 "WSS configuration validated for domain: $POLKADOT_WSS_DOMAIN"
fi

# Check memory requirements
if command -v free >/dev/null 2>&1; then
    FREE_MEMORY=$(free -m | awk '/^Mem:/{print $7}')
    MIN_MEMORY=2048
    
    case "${POLKADOT_NODE_TYPE:-full}" in
        "validator"|"full")
            MIN_MEMORY=4096
            ;;
        "light")
            MIN_MEMORY=1024
            ;;
    esac
    
    if [ "$FREE_MEMORY" -lt "$MIN_MEMORY" ]; then
        echo "Warning: Insufficient memory for ${POLKADOT_NODE_TYPE} node"
        echo "Available: ${FREE_MEMORY}MB, Recommended: ${MIN_MEMORY}MB"
    fi
fi

echo "Preparation completed successfully."
echo ""
echo "Node configuration:"
echo "- Type: ${POLKADOT_NODE_TYPE:-full}"
echo "- Chain: ${POLKADOT_CHAIN:-polkadot}"
echo "- Archive mode: ${POLKADOT_ARCHIVE_MODE:-false}"
echo "- Pruning enabled: ${POLKADOT_PRUNING_ENABLED:-true}"
echo "- WSS enabled: ${POLKADOT_WSS_ENABLED:-false}"
echo "- Data path: ${POLKADOT_BASE_PATH:-/var/lib/polkadot/data}"