#!/bin/bash

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

# Function to print status messages
print_status() {
    echo -e "${GREEN}[*] $1${NC}"
}

print_error() {
    echo -e "${RED}[!] $1${NC}"
}

print_warning() {
    echo -e "${YELLOW}[!] $1${NC}"
}

# Check if running as root
if [ "$EUID" -ne 0 ]; then
    print_error "Please run this script as root (use sudo)"
    exit 1
fi

# Detect distribution
if [ -f /etc/os-release ]; then
    . /etc/os-release
    OS=$NAME
    VER=$VERSION_ID
else
    print_error "Could not detect distribution"
    exit 1
fi

print_status "Detected OS: $OS $VER"

# Define packages based on distribution
case $OS in
    "Ubuntu"|"Debian GNU/Linux")
        # Common packages for both Ubuntu and Debian
        PACKAGES="cmake make g++ devscripts debhelper libtbb-dev libxxhash-dev"
        ;;
    *)
        print_error "Unsupported distribution: $OS"
        exit 1
        ;;
esac

# Function to check if a package is installed
is_package_installed() {
    dpkg -l "$1" 2>/dev/null | grep -q "^ii"
}

# Install missing packages
print_status "Checking and installing required packages..."
for pkg in $PACKAGES; do
    if ! is_package_installed "$pkg"; then
        print_status "Installing $pkg..."
        apt-get install -y "$pkg"
        if [ $? -ne 0 ]; then
            print_error "Failed to install $pkg"
            exit 1
        fi
    else
        print_status "$pkg is already installed"
    fi
done

# Update package lists
print_status "Updating package lists..."
apt-get update

# Verify all required tools are installed
print_status "Verifying installation..."
for tool in cmake make g++; do
    if ! command -v "$tool" &> /dev/null; then
        print_error "$tool is not installed properly"
        exit 1
    fi
done

# Check TBB installation
if [ ! -d "/usr/include/tbb" ]; then
    print_error "TBB headers not found"
    exit 1
fi

# # Check Boost installation
# if [ ! -d "/usr/include/boost" ]; then
#     print_error "Boost headers not found"
#     exit 1
# fi

print_status "All dependencies installed successfully!"
print_status "You can now run ./build.sh to build the project" 