#!/bin/bash

# Parse command line arguments
BUILD_ONLY=false
BUILD_LIBS=true
BUILD_DRIVERS=true

while getopts "bld" opt; do
    case ${opt} in
        b )
            BUILD_ONLY=true
            ;;
        l )
            BUILD_DRIVERS=false
            ;;
        d )
            BUILD_LIBS=false
            ;;
    esac
done

# Function to check if a command exists
command_exists() {
    command -v "$1" >/dev/null 2>&1
}

# Function to install dependencies
install_dependencies() {
    # Download and verify dependencies
    deps_url="https://stellarmate.com/jdownloads/dependencies/$DEPS_FILE"
    echo "Downloading dependencies from $deps_url"
    deps_list=$(wget -qO- "$deps_url")

    if [ -z "$deps_list" ]; then
        echo "Error: Failed to download dependencies from $deps_url"
        exit 1
    fi

    echo "Dependencies to install: $deps_list"

    if [[ "$ID" == "arch" ]] || [[ "$ID_LIKE" == *"arch"* ]]; then
        echo "Detected Arch Linux. Installing dependencies using pacman..."
        sudo pacman -Syu --needed --noconfirm $deps_list
    else
        echo "Detected Debian/Ubuntu based system. Installing dependencies using apt-get..."
        # Configure APT options as an array
        APT_OPTIONS=(-o 'Dpkg::Options::=--force-overwrite' --fix-broken -y)

        sudo dpkg --configure -a
        sudo apt-get update
        # Install dependencies with proper option handling
        sudo apt-get "${APT_OPTIONS[@]}" install $deps_list
    fi
}

build_drivers()
{
    mkdir -p ~/Projects/build/indi-3rdparty || return 1
    cd ~/Projects/build/indi-3rdparty || return 1
    
    if [ "$BUILD_LIBS" = true ]; then
        echo "Building 3rd party libraries..."
        cmake -G Ninja -DCMAKE_INSTALL_PREFIX=/usr -DCMAKE_BUILD_TYPE=Debug -DBUILD_LIBS=On ~/Projects/indi-3rdparty || return 1
        cmake --build . || return 1
        sudo cmake --install . || return 1
    fi
    
    if [ "$BUILD_DRIVERS" = true ]; then
        echo "Building 3rd party drivers..."
        cmake -G Ninja -DCMAKE_INSTALL_PREFIX=/usr -DCMAKE_BUILD_TYPE=Debug -DBUILD_LIBS=Off ~/Projects/indi-3rdparty || return 1
        cmake --build . || return 1
        sudo cmake --install . || return 1
    fi
    
    return 0
}

# Detect OS
if [ -f /etc/os-release ]; then
    . /etc/os-release
    # Check both ID and ID_LIKE for Ubuntu and its derivatives
    if [[ "$ID" == "ubuntu" ]] || [[ "$ID" == "kubuntu" ]] || [[ "$ID" == "neon" ]] || [[ "$ID_LIKE" == *"ubuntu"* ]]; then
        DEPS_FILE="indi-3rdparty-ubuntu.txt"
    elif [[ "$ID" == "arch" ]] || [[ "$ID_LIKE" == *"arch"* ]]; then # Check for Arch Linux
        DEPS_FILE="indi-3rdparty-arch.txt"
    else
        DEPS_FILE="indi-3rdparty.txt" # Default for Debian and others
    fi
else
    echo "Cannot detect OS, defaulting to Debian configuration"
    DEPS_FILE="indi-3rdparty.txt"
fi

# Install dependencies if essential tools are missing or if build directory doesn't exist
if ! command_exists git || ! command_exists cmake || [ ! -d ~/Projects/build/indi-3rdparty ]; then
    echo "Installing/reinstalling dependencies..."
    install_dependencies
fi

# Function to handle git operations
handle_git_operations() {
    if [ -d ~/Projects/indi-3rdparty ]; then
        git -C ~/Projects/indi-3rdparty pull
        return 0
    fi
    mkdir -p ~/Projects || true
    cd ~/Projects
    git clone --depth 1 https://github.com/indilib/indi-3rdparty.git
    return 0
}

# Main build flow
if [ "$BUILD_ONLY" = false ] || [ ! -d ~/Projects/indi-3rdparty ]; then
    echo "Updating/cloning INDI 3rd party drivers source..."
    handle_git_operations
fi

# Ensure source directory exists before attempting build
if [ ! -d ~/Projects/indi-3rdparty ]; then
    echo "Error: Source directory ~/Projects/indi-3rdparty not found"
    exit 1
fi

# Try building
if ! build_drivers; then
    echo "Build error. Cleaning INDI 3rd Party building directory and trying again"
    rm -rf ~/Projects/build/indi-3rdparty
    if ! build_drivers; then
        echo "Build failed again after cleanup. Aborting."
        exit 1
    fi
fi
