#!/bin/bash

# Parse command line options
SKIP_GIT=false
while getopts "b" opt; do
    case ${opt} in
        b)
            SKIP_GIT=true
            ;;
        \?)
            echo "Usage: $0 [-b] (use -b to skip git operations and build directly)"
            exit 1
            ;;
    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..."
        SCRIPT_DIR=$(dirname "$(readlink -f "$0")")
        sudo pacman --config "$SCRIPT_DIR/pacman-build.conf" -Sy --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_indi()
{
    mkdir -p ~/Projects/build/indi-core || return 1
    cd ~/Projects/build/indi-core || return 1
    cmake -G Ninja -DCMAKE_INSTALL_PREFIX=/usr -DCMAKE_BUILD_TYPE=Debug ~/Projects/indi || return 1
    cmake --build . || return 1
    sudo cmake --install . || return 1
    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-core-ubuntu.txt"
    elif [[ "$ID" == "arch" ]] || [[ "$ID_LIKE" == *"arch"* ]]; then # Check for Arch Linux
        DEPS_FILE="indi-core-arch.txt"
    else
        DEPS_FILE="indi-core.txt" # Default for Debian and others
    fi
else
    echo "Cannot detect OS, defaulting to Debian configuration"
    DEPS_FILE="indi-core.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-core ]; then
    echo "Installing/reinstalling dependencies..."
    install_dependencies
fi

# Try building if directory exists
if [ -d ~/Projects/build/indi-core ]; then
    if [ "$SKIP_GIT" = false ]; then
        git -C ~/Projects/indi pull
    fi
    if ! build_indi; then
        echo "Build error. Cleaning INDI Core building directory and trying again"
        rm -rf ~/Projects/build/indi-core
        if ! build_indi; then
            echo "Build failed again after cleanup. Aborting."
            exit 1
        fi
    fi
    exit 0
fi
# Only clone if git operations are not skipped
if [ "$SKIP_GIT" = false ]; then
    mkdir -p ~/Projects || true
    cd ~/Projects
    git clone --depth 1 https://github.com/indilib/indi.git
fi

# Try fresh build
if ! build_indi; then
    echo "Build error. Cleaning and trying one more time"
    rm -rf ~/Projects/build/indi-core
    if ! build_indi; then
        echo "Build failed again after cleanup. Aborting."
        exit 1
    fi
fi
