#!/bin/bash

# BestCDN C++ Build Script

echo "BestCDN C++ High-Performance Tester Build Script"
echo "================================================"

# Check if we're on Linux
if [[ "$OSTYPE" == "linux-gnu"* ]]; then
    echo "Detected Linux system"
    
    # Check if dependencies are installed
    if ! pkg-config --exists libcurl; then
        echo "Installing dependencies..."
        if command -v apt-get &> /dev/null; then
            sudo apt-get update
            sudo apt-get install -y libcurl4-openssl-dev libjsoncpp-dev build-essential pkg-config
        elif command -v yum &> /dev/null; then
            sudo yum install -y libcurl-devel jsoncpp-devel gcc-c++ make pkgconfig
        elif command -v dnf &> /dev/null; then
            sudo dnf install -y libcurl-devel jsoncpp-devel gcc-c++ make pkgconfig
        else
            echo "Error: Package manager not found. Please install libcurl-dev and libjsoncpp-dev manually."
            exit 1
        fi
    fi
    
elif [[ "$OSTYPE" == "darwin"* ]]; then
    echo "Detected macOS system"
    
    # Check if Homebrew is installed
    if ! command -v brew &> /dev/null; then
        echo "Error: Homebrew not found. Please install Homebrew first."
        exit 1
    fi
    
    # Install dependencies
    echo "Installing dependencies..."
    brew install curl jsoncpp pkg-config
    
else
    echo "Unsupported operating system: $OSTYPE"
    exit 1
fi

# Create results directory
echo "Creating results directory..."
mkdir -p results

# Build the C++ tester
echo "Building C++ tester..."
cd src/cpp

# Use pkg-config to get proper flags
if pkg-config --exists libcurl; then
    CURL_FLAGS=$(pkg-config --cflags --libs libcurl)
else
    CURL_FLAGS="-lcurl"
fi

if pkg-config --exists jsoncpp; then
    JSONCPP_FLAGS=$(pkg-config --cflags --libs jsoncpp)
else
    JSONCPP_FLAGS="-ljsoncpp"
fi

echo "Building with flags: $CURL_FLAGS $JSONCPP_FLAGS"

g++ -std=c++17 -O3 -Wall -Wextra -pthread \
    bestcdn_tester.cpp \
    $CURL_FLAGS $JSONCPP_FLAGS \
    -o bestcdn_tester

if [ $? -eq 0 ]; then
    echo "✓ Build successful!"
    echo ""
    echo "To run the C++ tester:"
    echo "  cd src/cpp"
    echo "  ./bestcdn_tester"
    echo ""
    echo "Make sure your IP lists are in the ip_lists/ directory:"
    echo "  - ip_lists/cloudflare.txt"
    echo "  - ip_lists/fastly.txt"
    echo "  - ip_lists/edgeone.txt"
    echo "  - ip_lists/esa.txt"
else
    echo "✗ Build failed!"
    exit 1
fi