#!/bin/bash

# Script d'installation pour tous les outils avancés Warfactory
# Installe fuzzing, formal verification, concurrency analysis, etc.

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"

echo "🔧 Setting up Warfactory Advanced Tools..."
echo ""

# Detect OS
if [[ "$OSTYPE" == "linux-gnu"* ]]; then
    OS="linux"
    DISTRO=$(lsb_release -si 2>/dev/null || echo "Unknown")
elif [[ "$OSTYPE" == "darwin"* ]]; then
    OS="macos"
else
    echo "❌ Unsupported OS: $OSTYPE"
    exit 1
fi

echo "🖥️  Detected OS: $OS"
echo ""

# =============================================================================
# FUZZING TOOLS
# =============================================================================

echo "🔍 Installing Fuzzing Tools..."

# AFL++
if ! command -v afl-fuzz &> /dev/null; then
    echo "  Installing AFL++..."
    if [[ "$OS" == "linux" ]]; then
        if [[ "$DISTRO" == "Ubuntu" ]] || [[ "$DISTRO" == "Debian" ]]; then
            sudo apt-get update
            sudo apt-get install -y afl++
        elif [[ "$DISTRO" == "Fedora" ]] || [[ "$DISTRO" == "CentOS" ]]; then
            sudo dnf install -y afl
        else
            # Build from source
            git clone https://github.com/AFLplusplus/AFLplusplus.git /tmp/aflplusplus
            cd /tmp/aflplusplus
            make all
            sudo make install
        fi
    elif [[ "$OS" == "macos" ]]; then
        brew install afl++
    fi
    echo "  ✓ AFL++ installed"
else
    echo "  ✓ AFL++ already installed"
fi

# honggfuzz
if ! command -v honggfuzz &> /dev/null; then
    echo "  Installing honggfuzz..."
    if [[ "$OS" == "linux" ]]; then
        if [[ "$DISTRO" == "Ubuntu" ]] || [[ "$DISTRO" == "Debian" ]]; then
            sudo apt-get install -y honggfuzz
        else
            # Build from source
            git clone https://github.com/google/honggfuzz.git /tmp/honggfuzz
            cd /tmp/honggfuzz
            make
            sudo make install
        fi
    elif [[ "$OS" == "macos" ]]; then
        brew install honggfuzz
    fi
    echo "  ✓ honggfuzz installed"
else
    echo "  ✓ honggfuzz already installed"
fi

# =============================================================================
# FORMAL VERIFICATION TOOLS
# =============================================================================

echo ""
echo "🔬 Installing Formal Verification Tools..."

# CBMC
if ! command -v cbmc &> /dev/null; then
    echo "  Installing CBMC..."
    if [[ "$OS" == "linux" ]]; then
        if [[ "$DISTRO" == "Ubuntu" ]] || [[ "$DISTRO" == "Debian" ]]; then
            sudo apt-get install -y cbmc
        else
            # Download binary release
            CBMC_VERSION="5.95.1"
            wget "https://github.com/diffblue/cbmc/releases/download/cbmc-${CBMC_VERSION}/cbmc-${CBMC_VERSION}-linux-64.tgz" -O /tmp/cbmc.tgz
            cd /tmp
            tar -xzf cbmc.tgz
            sudo cp cbmc-*/bin/* /usr/local/bin/
        fi
    elif [[ "$OS" == "macos" ]]; then
        brew install cbmc
    fi
    echo "  ✓ CBMC installed"
else
    echo "  ✓ CBMC already installed"
fi

# KLEE (plus complexe, nécessite LLVM)
if ! command -v klee &> /dev/null; then
    echo "  Installing KLEE..."
    if [[ "$OS" == "linux" ]]; then
        # KLEE is complex to build, use Docker image instead
        echo "  📦 KLEE will use Docker image (recommended)"
        echo "     Run: docker pull klee/klee"
        echo "     Usage: docker run --rm -v \$(pwd):/tmp klee/klee klee /tmp/your_file.bc"
    elif [[ "$OS" == "macos" ]]; then
        echo "  📦 KLEE installation on macOS requires manual setup"
        echo "     See: https://klee.github.io/build-llvm9/"
    fi
else
    echo "  ✓ KLEE already installed"
fi

# =============================================================================
# STATIC ANALYSIS TOOLS
# =============================================================================

echo ""
echo "🔍 Installing Static Analysis Tools..."

# Cppcheck
if ! command -v cppcheck &> /dev/null; then
    echo "  Installing Cppcheck..."
    if [[ "$OS" == "linux" ]]; then
        if [[ "$DISTRO" == "Ubuntu" ]] || [[ "$DISTRO" == "Debian" ]]; then
            sudo apt-get install -y cppcheck
        elif [[ "$DISTRO" == "Fedora" ]] || [[ "$DISTRO" == "CentOS" ]]; then
            sudo dnf install -y cppcheck
        fi
    elif [[ "$OS" == "macos" ]]; then
        brew install cppcheck
    fi
    echo "  ✓ Cppcheck installed"
else
    echo "  ✓ Cppcheck already installed"
fi

# ABI compliance checker
if ! command -v abi-compliance-checker &> /dev/null; then
    echo "  Installing ABI Compliance Checker..."
    if [[ "$OS" == "linux" ]]; then
        if [[ "$DISTRO" == "Ubuntu" ]] || [[ "$DISTRO" == "Debian" ]]; then
            sudo apt-get install -y abi-compliance-checker
        else
            # Install from source
            git clone https://github.com/lvc/abi-compliance-checker.git /tmp/abi-checker
            cd /tmp/abi-checker
            sudo make install prefix=/usr/local
        fi
    elif [[ "$OS" == "macos" ]]; then
        # Build from source
        git clone https://github.com/lvc/abi-compliance-checker.git /tmp/abi-checker
        cd /tmp/abi-checker
        sudo make install prefix=/usr/local
    fi
    echo "  ✓ ABI Compliance Checker installed"
else
    echo "  ✓ ABI Compliance Checker already installed"
fi

# =============================================================================
# CONCURRENCY ANALYSIS TOOLS
# =============================================================================

echo ""
echo "🧵 Installing Concurrency Analysis Tools..."

# Valgrind
if ! command -v valgrind &> /dev/null; then
    echo "  Installing Valgrind..."
    if [[ "$OS" == "linux" ]]; then
        if [[ "$DISTRO" == "Ubuntu" ]] || [[ "$DISTRO" == "Debian" ]]; then
            sudo apt-get install -y valgrind
        elif [[ "$DISTRO" == "Fedora" ]] || [[ "$DISTRO" == "CentOS" ]]; then
            sudo dnf install -y valgrind
        fi
    elif [[ "$OS" == "macos" ]]; then
        brew install --HEAD valgrind
    fi
    echo "  ✓ Valgrind installed"
else
    echo "  ✓ Valgrind already installed"
fi

# =============================================================================
# GUIDELINES SUPPORT LIBRARY
# =============================================================================

echo ""
echo "📋 Setting up Guidelines Support Library..."

GSL_DIR="$PROJECT_ROOT/third_party/gsl"
if [[ ! -d "$GSL_DIR" ]]; then
    echo "  Cloning Microsoft GSL..."
    git clone https://github.com/microsoft/GSL.git "$GSL_DIR"
    echo "  ✓ GSL cloned to third_party/gsl"
else
    echo "  ✓ GSL already available"
fi

# =============================================================================
# VERIFICATION
# =============================================================================

echo ""
echo "✅ Verifying installations..."

TOOLS=(
    "afl-fuzz:AFL++"
    "honggfuzz:honggfuzz"
    "cbmc:CBMC"
    "cppcheck:Cppcheck"
    "valgrind:Valgrind"
    "abi-compliance-checker:ABI Checker"
    "clang:Clang (for libFuzzer)"
    "llvm-profdata:LLVM tools"
)

for tool_info in "${TOOLS[@]}"; do
    tool="${tool_info%:*}"
    name="${tool_info#*:}"

    if command -v "$tool" &> /dev/null; then
        echo "  ✓ $name: $(which $tool)"
    else
        echo "  ❌ $name: not found"
    fi
done

echo ""
echo "🎯 Setup complete!"
echo ""
echo "📖 Usage examples:"
echo "  mkdir build && cd build"
echo "  cmake -DCMAKE_BUILD_TYPE=Debug -DENABLE_ADVANCED_TOOLS=ON .."
echo "  make economy-engine"
echo ""
echo "🔍 Run fuzzing:"
echo "  make economy-engine_fuzz_all"
echo ""
echo "🔬 Run formal verification:"
echo "  make economy-engine_cbmc"
echo ""
echo "🧵 Run concurrency analysis:"
echo "  make economy-engine_helgrind"
echo ""
echo "📊 Generate coverage report:"
echo "  make economy-engine_coverage_run"
echo ""
echo "🔗 Check ABI compatibility:"
echo "  make economy-engine_abi_check"