#!/bin/bash

# Shared distro helpers for install scripts.

SCRIPT_LIB_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
REPO_ROOT="${REPO_ROOT:-$(dirname "$(dirname "$SCRIPT_LIB_DIR")")}"
REBOOT_MARKER="${REBOOT_MARKER:-$REPO_ROOT/.setup-reboot-required}"

if [ -f /etc/os-release ]; then
    . /etc/os-release
    OS="${ID}"
    OS_LIKE="${ID_LIKE:-}"
else
    echo "Unable to detect operating system: /etc/os-release not found."
    return 1 2>/dev/null || exit 1
fi

is_arch_family() {
    [[ "$OS" == "arch" || "$OS" == "manjaro" || " $OS_LIKE " == *" arch "* ]]
}

is_debian_family() {
    [[ "$OS" == "ubuntu" || "$OS" == "debian" || " $OS_LIKE " == *" debian "* ]]
}

is_fedora_family() {
    [[ "$OS" == "fedora" || "$OS" == "bazzite" || " $OS_LIKE " == *" fedora "* || " $OS_LIKE " == *" rhel "* ]]
}

is_atomic_fedora() {
    is_fedora_family && command -v rpm-ostree >/dev/null 2>&1 && [ -f /run/ostree-booted ]
}

mark_reboot_required() {
    touch "$REBOOT_MARKER"
    echo ""
    echo "    REBOOT REQUIRED: Fedora atomic package layering finished."
    echo "    Please reboot, then rerun the same make target."
    echo ""
}

install_packages() {
    local packages=("$@")

    if [ ${#packages[@]} -eq 0 ]; then
        return 0
    fi

    if is_arch_family; then
        sudo pacman -S --noconfirm --needed "${packages[@]}"
        return 0
    fi

    if is_debian_family; then
        sudo DEBIAN_FRONTEND=noninteractive apt-get update
        sudo DEBIAN_FRONTEND=noninteractive apt-get install -y "${packages[@]}"
        return 0
    fi

    if is_fedora_family; then
        if is_atomic_fedora; then
            local missing_packages=()
            local pkg

            for pkg in "${packages[@]}"; do
                rpm -q "$pkg" >/dev/null 2>&1 || missing_packages+=("$pkg")
            done

            if [ ${#missing_packages[@]} -eq 0 ]; then
                return 0
            fi

            sudo rpm-ostree install "${missing_packages[@]}"
            mark_reboot_required
            return 42
        fi

        sudo dnf install -y "${packages[@]}"
        return 0
    fi

    echo "Unsupported OS: $OS"
    return 1
}
