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

echo "Preparing Polkadot Solochain installation..."

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

# 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 git >/dev/null 2>&1 || { echo "git 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; }

# Check if Rust is available or if we need to install it
if ! command -v rustc >/dev/null 2>&1; then
    echo "Rust not found - will be installed during setup"
else
    RUST_VERSION=$(rustc --version | awk '{print $2}')
    echo "Found Rust version: $RUST_VERSION"
fi

# Check for essential build tools
if ! command -v gcc >/dev/null 2>&1 && ! command -v clang >/dev/null 2>&1; then
    echo "No C compiler found. GCC or Clang is required for building."
fi

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

# Check available disk space (Polkadot build requires significant space)
AVAILABLE_SPACE=$(df /opt 2>/dev/null | awk 'NR==2 {print $4}' || echo "0")
REQUIRED_SPACE=5000000  # 5GB in KB
if [ "$AVAILABLE_SPACE" -ne "0" ] && [ "$AVAILABLE_SPACE" -lt "$REQUIRED_SPACE" ]; then
    echo "Warning: Low disk space. Polkadot build requires at least 5GB free space."
    echo "Available: $(($AVAILABLE_SPACE / 1024))MB, Required: $(($REQUIRED_SPACE / 1024))MB"
fi

# Check available memory (Rust compilation is memory intensive)
if command -v free >/dev/null 2>&1; then
    FREE_MEMORY=$(free -m | awk '/^Mem:/{print $7}')
    if [ "$FREE_MEMORY" -lt 2048 ]; then
        echo "Warning: Less than 2GB of free memory. Polkadot compilation may be slow or fail."
        echo "Consider adding swap space or using a machine with more RAM."
    fi
fi

# Check port availability
RPC_PORT=${POLKADOT_RPC_PORT:-9944}
WS_PORT=${POLKADOT_WS_PORT:-9944}
HTTP_PORT=${POLKADOT_HTTP_PORT:-9933}
P2P_PORT=30333

for port in $RPC_PORT $WS_PORT $HTTP_PORT $P2P_PORT; 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 network configuration
if [ -n "$POLKADOT_PUBLIC_ADDR" ]; then
    echo "Public address configured: $POLKADOT_PUBLIC_ADDR"
fi

if [ -n "$POLKADOT_BOOTNODES" ]; then
    echo "Bootnodes configured: $POLKADOT_BOOTNODES"
fi

# Validate runtime configuration
if [ "${POLKADOT_PVM_ENABLED:-true}" = "true" ]; then
    echo "PVM (Polkadot Virtual Machine) support enabled"
fi

case "${POLKADOT_WASM_EXECUTION:-compiled}" in
    "compiled"|"interpreted")
        echo "WASM execution mode: ${POLKADOT_WASM_EXECUTION}"
        ;;
    *)
        echo "Invalid WASM execution mode: ${POLKADOT_WASM_EXECUTION}" >&2
        exit 1
        ;;
esac

# Validate consensus configuration
case "${POLKADOT_CONSENSUS_ALGORITHM:-aura}" in
    "aura"|"babe")
        echo "Consensus algorithm: ${POLKADOT_CONSENSUS_ALGORITHM}"
        ;;
    *)
        echo "Invalid consensus algorithm: ${POLKADOT_CONSENSUS_ALGORITHM}" >&2
        exit 1
        ;;
esac

# Check development mode settings
if [ "${POLKADOT_DEV_MODE:-false}" = "true" ]; then
    echo "Development mode enabled - Alice validator keys will be configured"
fi

# Validate validator configuration
if [ "${POLKADOT_VALIDATOR_ENABLED:-false}" = "true" ]; then
    echo "Validator mode enabled"
    if [ -z "$POLKADOT_SESSION_KEYS" ] && [ "${POLKADOT_DEV_MODE:-false}" != "true" ]; then
        echo "Warning: Validator enabled but no session keys configured"
    fi
fi

# Check telemetry configuration
if [ "${POLKADOT_TELEMETRY_ENABLED:-false}" = "true" ]; then
    if [ -z "$POLKADOT_TELEMETRY_URL" ]; then
        echo "Warning: Telemetry enabled but no URL configured"
    else
        echo "Telemetry enabled: $POLKADOT_TELEMETRY_URL"
    fi
fi

# Validate pruning configuration
case "${POLKADOT_PRUNING:-256}" in
    "archive"|[0-9]*)
        echo "Pruning configuration: ${POLKADOT_PRUNING}"
        ;;
    *)
        echo "Invalid pruning configuration: ${POLKADOT_PRUNING}" >&2
        exit 1
        ;;
esac

echo "Preparation completed successfully."
echo ""
echo "Build information:"
echo "- This installation will clone and build the Polkadot solochain template"
echo "- Build time: 20-30 minutes on modern hardware"
echo "- PVM support: ${POLKADOT_PVM_ENABLED:-true}"
echo "- Consensus: ${POLKADOT_CONSENSUS_ALGORITHM:-aura} + ${POLKADOT_FINALITY:-grandpa}"
echo "- RPC ports: ${RPC_PORT} (WS), ${HTTP_PORT} (HTTP)"
echo "- Data path: ${POLKADOT_BASE_PATH:-/var/lib/polkadot/data}"