#!/bin/bash
#
# archhw - Arch-native hardware, driver and kernel helper for ToolBox.
#
# Usage: archhw [command] [options]
#
#   detect                PCI display devices: slot, class, vendor, driver in use
#   list                  drivers in use + installed driver packages + kernels
#   kernels               installed and available kernel packages
#   installed-kernels     the installed kernel package names, one per line (for menus)
#   available-kernels     the kernel package names in the enabled repos, one per line
#   running-kernel        package that owns the running kernel (empty if unknown)
#   running-flavour       package name of the running kernel's flavour (never empty)
#   refresh-grub          regenerate /boot/grub/grub.cfg with backup, verify and restore
#   install-kernel <pkg>  install one or more kernel packages
#   remove-kernel <pkg>   remove kernel packages (never the running kernel)
#   install-open          open source graphics stack for the detected GPUs
#   install-proprietary   proprietary driver for the detected GPUs (NVIDIA only)
#
# Options:
#   --dry-run  print the root commands instead of running them
#   --yes      skip the confirmation prompt
#
# Environment overrides (defaults in parentheses):
#   BMENU_PCI_ROOT       (/sys/bus/pci/devices)   device tree to read
#   BMENU_PACMAN_CONF    (/etc/pacman.conf)       config to check for [multilib]
#   BMENU_PACMAN_SYNC_DIR (/var/lib/pacman/sync)  synced database directory
#   BMENU_BOOT_DIR       (/boot)                   boot loader location to detect
#   BMENU_PACMAN_DB_DIR  (/var/lib/pacman)         where db.lck is looked for
#   BMENU_MKINITCPIO_PRESET_DIR (/etc/mkinitcpio.d) preset directory to check
#   BMENU_UNAME_R        ($(uname -r))             kernel version the removal guard treats as running
#
# This program is free software; you can redistribute it and/or modify it under the
# terms of the GNU General Public License as published by the Free Software
# Foundation; either version 2 of the License, or (at your option) any later version.

# =======================
# Define Colors
RED='\e[41m'
GREEN='\e[32m'
NC='\e[0m' # No color
BG='\e[7m' # Highlighting Background color
TC='\e[1m' # Highlighting Text color

# =======================
# Service messages section
ERRORMSG="$RED Wrong option ${NC}"
TRYAGAINMSG=" Please try again..."
NOTROOTMSG="$RED This action needs root (sudo). ${NC}"
LOCKMSG="$RED Pacman seems to be in use (database lock). Try again after the other pacman finished. ${NC}"
NOPKGSMSG="$RED Nothing to do: no display device of class 03xx found. ${NC}"
MISSINGPKGMSG="$RED These packages are not available in your enabled repositories: ${NC}"
MULTILIBMSG=" 32-bit packages are skipped: [multilib] is not enabled in"
MULTILIBHOW=" Enable it yourself in that file, then run: sudo pacman -Syu"
NONVIDIAFREE=" The open source driver (nouveau) is the supported choice for this card."
# Package names archhw can hand to pacman
NVIDIA_UTILS="nvidia-utils nvidia-settings"
NVIDIA_32="lib32-nvidia-utils"

# =======================
# Locals
PCI_ROOT=${BMENU_PCI_ROOT:-/sys/bus/pci/devices}
PACMAN_CONF=${BMENU_PACMAN_CONF:-/etc/pacman.conf}
SYNC_DIR=${BMENU_PACMAN_SYNC_DIR:-/var/lib/pacman/sync}
DB_DIR=${BMENU_PACMAN_DB_DIR:-/var/lib/pacman}
BOOT_DIR=${BMENU_BOOT_DIR:-/boot}
PRESET_DIR=${BMENU_MKINITCPIO_PRESET_DIR:-/etc/mkinitcpio.d}
# Kernel package names this helper acts on: the Arch flavours plus the numbered
# packages of distros whose kernels are named per version
KERNEL_MATCH='^linux(-lts|-zen|-hardened|-lowlatency|[0-9]+(-rt)?)?$'
DRYRUN=0
ASSUME_YES=0

# =======================
# Small helpers

function is_dry() {
    [ "$DRYRUN" -eq 1 ]
}

# Break a long list at 80 columns, prefix repeated on every line
function wrap_list() { # <prefix> <text>
    local prefix="$1" line="" w
    shift
    local -a words=()
    read -r -a words <<< "$*"
    for w in "${words[@]}"; do
        if [ $(( ${#prefix} + ${#line} + ${#w} + 1 )) -gt 80 ]; then
            echo -e "${prefix}${line}${NC}"
            line="$w"
        else
            line="${line:+$line }$w"
        fi
    done
    [ -n "$line" ] && echo -e "${prefix}${line}${NC}"
}

# Run a root command, or only show it in dry-run mode
function run_root() {
    if is_dry; then
        wrap_list " ${TC}dry-run:${NC} " "$*"
        return 0
    fi
    "$@"
}

# Commit a prepared file onto a root-owned target: a staging copy next to it, then an
# atomic rename. A direct cp truncates the target first. The target's mode is kept
function commit_root_file() {
    local src="$1" dest="$2" real stage mode
    real=$(readlink -f "$dest" 2>/dev/null) || real="$dest"
    [ -n "$real" ] || real="$dest"
    mode=$(run_root sudo stat -c '%a' "$real" 2>/dev/null) || mode=""
    stage="$real.archhw-staging"
    if ! run_root sudo cp "$src" "$stage"; then
        run_root sudo rm -f "$stage"
        return 1
    fi
    [ -n "$mode" ] && run_root sudo chmod "$mode" "$stage"
    if ! run_root sudo mv -f "$stage" "$real"; then
        run_root sudo rm -f "$stage"
        return 1
    fi
    return 0
}

# pacman is locale-dependent, so force English for anything we parse
function pacman_query() {
    LC_ALL=C pacman "$@"
}

# Is a package name in one of the enabled repositories?
function pkg_available() {
    pacman_query -Si "$1" >/dev/null 2>&1
}

function multilib_enabled() {
    grep -qE '^[[:space:]]*\[multilib\][[:space:]]*$' "$PACMAN_CONF"
}

function db_locked() {
    [ -e "$DB_DIR/db.lck" ]
}

# Human readable vendor name for the PCI ids
function vendor_name() {
    case "$1" in
    1002) echo "AMD/ATI" ;;
    8086) echo "Intel" ;;
    10de) echo "NVIDIA" ;;
    15ad) echo "VMware" ;;
    1a03) echo "ASPEED" ;;
    1244) echo "SiPix" ;;
    1e60) echo "IBM pSeries" ;;
    *) echo "unknown vendor" ;;
    esac
}

function class_name() {
    case "$1" in
    0300) echo "VGA compatible controller" ;;
    0302) echo "3D controller" ;;
    0380) echo "Display controller" ;;
    *) echo "display controller (class $1)" ;;
    esac
}

# Kernel module bound to a PCI device, empty when there is none
function driver_in_use() {
    [ -L "$1/driver" ] || return 0
    basename "$(readlink -f "$1/driver")"
}

# Print one line per display device: slot|class|vendor|driver
function detect_gpus() {
    if [ ! -d "$PCI_ROOT" ]; then
        echo -e "$RED No PCI device tree at $PCI_ROOT ${NC}" >&2
        return 1
    fi
    local d cls ven drv found=0
    for d in "$PCI_ROOT"/*; do
        [ -r "$d/class" ] || continue
        cls=$(cat "$d/class" 2>/dev/null)
        cls=${cls#0x}
        cls=${cls:0:4}
        case "$cls" in
        03*) ;;
        *) continue ;;
        esac
        ven=$(cat "$d/vendor" 2>/dev/null)
        ven=${ven#0x}
        drv=$(driver_in_use "$d")
        found=1
        echo "$(basename "$d")|${cls}|${ven}|${drv}"
    done
    [ "$found" -eq 1 ] || return 1
}

# Which kernel package provides the running kernel
function running_kernel_package() {
    local owner pkg uname_r
    uname_r=${BMENU_UNAME_R:-$(uname -r)}
    owner=$(pacman_query -Qo "/lib/modules/$uname_r" 2>/dev/null)
    # pacman output: "<path> is owned by <pkg> <ver>" (older wording: "is in")
    pkg=$(echo "$owner" | awk '{ for (i = 1; i <= NF; i++) if ($i == "by" || $i == "in") { print $(i + 1); exit } }')
    if [ -n "$pkg" ]; then
        echo "$pkg"
        return 0
    fi
    # Container or non-pacman kernel: derive the flavour from the version suffix
    case "$uname_r" in
    *-lts) echo "linux-lts" ;;
    *-zen) echo "linux-zen" ;;
    *-hardened) echo "linux-hardened" ;;
    *-lowlatency) echo "linux-lowlatency" ;;
    *) echo "" ;;
    esac
}

# The version string treated as the running kernel
function running_version() {
    printf '%s\n' "${BMENU_UNAME_R:-$(uname -r)}"
}

# Package name of the running kernel's flavour, never empty. A distro with
# numbered kernel packages names them after the major.minor of the version
function running_kernel_flavour() {
    local uname_r maj min rest rt pkg
    uname_r=$(running_version)
    case "$uname_r" in
    *-lts) echo "linux-lts"; return 0 ;;
    *-zen) echo "linux-zen"; return 0 ;;
    *-hardened) echo "linux-hardened"; return 0 ;;
    *-lowlatency) echo "linux-lowlatency"; return 0 ;;
    esac
    maj=${uname_r%%.*}
    rest=${uname_r#*.}
    min=${rest%%.*}
    if ! [[ $maj =~ ^[0-9]+$ ]] || ! [[ $min =~ ^[0-9]+$ ]]; then
        echo "linux"
        return 0
    fi
    rt=""
    # The rt marker can sit after the release, not before it
    case "$uname_r" in *-rt* | *.rt*) rt="-rt" ;; esac
    pkg="linux${maj}${min}${rt}"
    if installed_kernels | grep -qxF -- "$pkg"; then
        echo "$pkg"
    else
        echo "linux"
    fi
}

# Kernel packages offered by the enabled repositories
function available_kernels() {
    pacman_query -Sl 2>/dev/null | awk -v re="$KERNEL_MATCH" '$2 ~ re {print $2}' | sort
}

# Kernel packages that are installed
function installed_kernels() {
    pacman_query -Q 2>/dev/null | awk -v re="$KERNEL_MATCH" '$1 ~ re {print $1}' | sort
}

# Packages for the open source stack of one vendor
function open_packages() {
    case "$1" in
    1002) echo "mesa vulkan-radeon xf86-video-amdgpu" ;;
    8086) echo "mesa vulkan-intel" ;;
    10de) echo "mesa vulkan-nouveau xf86-video-nouveau" ;;
    *) echo "mesa" ;;
    esac
}

# 32-bit companions of the open stack, only when [multilib] is enabled
function open_packages_32() {
    case "$1" in
    1002) echo "lib32-mesa lib32-vulkan-radeon" ;;
    8086) echo "lib32-mesa lib32-vulkan-intel" ;;
    10de) echo "lib32-mesa lib32-vulkan-nouveau" ;;
    *) echo "lib32-mesa" ;;
    esac
}

# Proprietary driver packages for one vendor, chosen by the flavour of the running
# kernel. A prebuilt package is used only when the repositories have it, else DKMS
function proprietary_base() { # <vendor>
    local flavour base
    case "$1" in
    10de)
        flavour=$(running_kernel_flavour)
        case "$flavour" in
        linux) base="nvidia-open" ;;
        linux-lts) base="nvidia-open-lts" ;;
        *) base="nvidia-open-dkms" ;;
        esac
        if ! pkg_available "$base"; then
            base="nvidia-open-dkms"
        fi
        echo "$base"
        ;;
    *) echo "" ;;
    esac
}

function proprietary_packages() {
    case "$1" in
    10de) echo "$(proprietary_base "$1") $NVIDIA_UTILS" ;;
    *) echo "" ;;
    esac
}

# The headers a DKMS build needs, a prebuilt variant needs none. They follow the
# package that owns the running modules, the flavour name is the fallback
function proprietary_headers() { # <base package>
    local base="$1" pkg
    case "$base" in
    *-dkms) ;;
    *) echo ""; return 0 ;;
    esac
    pkg=$(running_kernel_package)
    [ -n "$pkg" ] || pkg=$(running_kernel_flavour)
    pkg_available "$pkg-headers" && echo "$pkg-headers"
}

# Read a whole line as the answer to a root prompt. An empty line is ENTER (yes),
# `n` refuses, EOF cancels
function ask_line() { # <prompt> -> sets $answer ("" = ENTER), rc 1 on EOF without any value
    printf '%s' "$1"
    answer=""
    if ! read -r answer; then
        # A last line without a trailing newline still carries the answer
        [ -n "$answer" ] || return 1
    fi
    return 0
}

# Show what will happen and ask for confirmation
function ask_confirm() {
    local text="$*"
    echo -e "\n $BG$TC $ACTION ${NC}"
    wrap_list " ${TC}" "$text"
    echo ""
    if is_dry; then
        echo -e " ${TC}dry-run: nothing will be executed.${NC}"
        return 0
    fi
    if [ "$ASSUME_YES" -eq 1 ]; then
        return 0
    fi
    echo -e " $BG Do you want to continue? [Y|n] ${NC}"
    # An empty line means yes, only `n` refuses, EOF cancels
    if ! ask_line ""; then
        echo -e " ${TC}No input, so nothing was confirmed. Cancelled. Use --yes for an unattended run.${NC}"
        return 1
    fi
    case "$answer" in
    n | N | no | NO)
        echo -e " ${TC}Cancelled.${NC}"
        return 1
        ;;
    esac
    return 0
}

function confirm_install() {
    ACTION="About to install"
    ask_confirm "$*"
}

function confirm_remove() {
    ACTION="About to remove"
    ask_confirm "$*"
}

# Deduplicate package names; empty input stays empty
function dedupe_pkgs() {
    local out="" p
    for p in "$@"; do
        case " $out " in
        *" $p "*) continue ;;
        esac
        out="$out $p"
    done
    echo $out
}

# Abort when the pacman database is not synced
function require_synced_db() {
    if [ ! -e "$SYNC_DIR/core.db" ]; then
        echo -e " $RED The pacman database is not synced yet. Run: sudo pacman -Syu ${NC}"
        return 1
    fi
    return 0
}

# Abort when a package is missing, so nothing is installed half-way
function check_packages() {
    local p missing=""
    require_synced_db || return 1
    for p in "$@"; do
        pkg_available "$p" || missing="$missing $p"
    done
    if [ -n "$missing" ]; then
        echo -e "$MISSINGPKGMSG$TC$missing${NC}"
        if multilib_enabled; then
            echo -e " Check your mirror list; the names above should exist in the enabled repositories."
        else
            echo -e " $MULTILIBMSG $PACMAN_CONF."
            echo -e " archhw never writes $PACMAN_CONF. Enable it yourself: add these two lines, then run sudo pacman -Syu"
            echo -e "   [multilib]"
            echo -e "   Include = /etc/pacman.d/mirrorlist"
        fi
        return 1
    fi
    return 0
}

# Common guard before any package transaction
function guard_transaction() {
    if db_locked; then
        echo -e "$LOCKMSG"
        return 1
    fi
    if ! is_dry; then
        if ! sudo -v 2>/dev/null; then
            echo -e "$NOTROOTMSG"
            return 1
        fi
    fi
    return 0
}

# Refresh the boot loader after a kernel changed, so the new/removed kernel is used
function bootloader_refresh() {
    if [ -d "$BOOT_DIR/grub" ]; then
        echo -e " ${TC}Boot loader: GRUB ${NC}"
        confirm_install_refresh "sudo grub-mkconfig -o $BOOT_DIR/grub/grub.cfg"
    elif [ -d "$BOOT_DIR/loader" ]; then
        echo -e " ${TC}Boot loader: systemd-boot ${NC}"
        confirm_install_refresh "sudo mkinitcpio -P"
    elif [ -e "$BOOT_DIR/refind_linux.conf" ]; then
        echo -e " ${TC}Boot loader: rEFInd ${NC} - it finds kernels automatically, nothing to refresh."
    else
        echo -e " ${TC}No boot loader detected${NC} (no $BOOT_DIR/grub, $BOOT_DIR/loader or $BOOT_DIR/refind_linux.conf)."
        echo -e " If this system boots from a boot loader, refresh its configuration after the kernel change."
    fi
}

function confirm_install_refresh() {
    local cmd="$*"
    echo -e " Refresh the boot loader configuration with:"
    echo -e "   $TC$cmd${NC}"
    # The grub and mkinitcpio wrappers run first, also with --yes
    if [ "$cmd" == "sudo grub-mkconfig -o $BOOT_DIR/grub/grub.cfg" ]; then
        refresh_grub
        return $?
    fi
    if [ "$cmd" == "sudo mkinitcpio -P" ]; then
        refresh_mkinitcpio
        return $?
    fi
    if is_dry; then
        echo -e " ${TC}dry-run: nothing is executed.${NC}"
        return 0
    fi
    # A command without a wrapper reaches here
    if [ "$ASSUME_YES" -eq 1 ]; then
        run_root $cmd
        return $?
    fi
    echo -e " $BG Do you want to run it now? [Y|n] ${NC}"
    if ! ask_line ""; then
        echo -e " ${TC}No input, so the refresh was not confirmed. Run it yourself when ready: $cmd${NC}"
        return 0
    fi
    case "$answer" in
    n | N | no | NO)
        echo -e " ${TC}Skipped. Run the command above manually when you are ready.${NC}"
        return 0
        ;;
    esac
    run_root $cmd
    return $?
}

# GRUB: back up grub.cfg, regenerate, verify the result, restore on any problem
function refresh_grub() {
    local cfg="$BOOT_DIR/grub/grub.cfg" backup entries_after kernels_before kernels_after
    if is_dry; then
        echo -e " ${TC}dry-run: would back up $cfg and refresh it.${NC}"
        return 0
    fi
    if ! command -v grub-mkconfig >/dev/null 2>&1; then
        echo -e " ${TC}grub-mkconfig is not installed. The boot loader config was left untouched.${NC}"
        return 1
    fi
    # grub.cfg is mode 600 root:root, so every read goes through root
    if ! sudo test -r "$cfg"; then
        echo -e " ${TC}No readable $cfg. Refusing to generate one blindly.${NC}"
        echo -e " Generate it yourself when you are sure this system uses GRUB: sudo grub-mkconfig -o $cfg"
        return 1
    fi
    backup="$cfg.archhw-backup-$(date +%Y%m%d-%H%M%S)"
    run_root sudo cp -f "$cfg" "$backup" || { echo -e "$RED Backup failed, nothing was changed. $NC"; return 1; }
    sha_before=$(sudo sha256sum "$cfg" | cut -d' ' -f1)
    sha_bak=$(sudo sha256sum "$backup" | cut -d' ' -f1)
    if [ -z "$sha_bak" ] || [ "$sha_before" != "$sha_bak" ]; then
        echo -e "$RED Backup verification failed, nothing was changed. $NC"
        return 1
    fi
    echo -e " ${TC}Backup written and verified: $backup${NC}"
    kernels_before=$(sudo grep -cE '^[[:space:]]*menuentry .* with Linux ' "$cfg")
    if ! sudo grub-mkconfig -o "$cfg"; then
        echo -e "$RED grub-mkconfig failed. Restoring the backup. $NC"
        commit_root_file "$backup" "$cfg" || echo -e "$RED Restoring $cfg failed too. Do it by hand: sudo cp $backup $cfg $NC"
        return 1
    fi
    entries_after=$(sudo grep -cE '^[[:space:]]*(menuentry|submenu) ' "$cfg" 2>/dev/null)
    kernels_after=$(sudo grep -cE '^[[:space:]]*menuentry .* with Linux ' "$cfg" 2>/dev/null)
    if ! sudo test -s "$cfg" || [ "${entries_after:-0}" -eq 0 ]; then
        echo -e "$RED The new grub.cfg has no entries. Restoring the backup. $NC"
        commit_root_file "$backup" "$cfg" || echo -e "$RED Restoring $cfg failed too. Do it by hand: sudo cp $backup $cfg $NC"
        return 1
    fi
    if [ "${kernels_after:-0}" -lt "${kernels_before:-0}" ]; then
        echo -e " ${TC}Warning: the new config lists fewer kernel entries than before ($kernels_before -> $kernels_after).${NC}"
        echo -e " Old config kept at: $backup"
    fi
    echo -e "$GREEN GRUB configuration refreshed ($entries_after entries, $kernels_after kernels). Backup: $backup"
    # Keep the three newest backups
    old_backups=$(sudo ls -1t "$BOOT_DIR/grub"/grub.cfg.archhw-backup-* 2>/dev/null | tail -n +4)
    if [ -n "$old_backups" ]; then
        for b in $old_backups; do
            sudo rm -f "$b"
        done
        echo -e " ${TC}Removed $(echo "$old_backups" | wc -l) older backup(s), the three newest are kept.${NC}"
    fi
    return 0
}

# systemd-boot: presets are rebuilt; verify mkinitcpio exists and images are present
function refresh_mkinitcpio() {
    if is_dry; then
        echo -e " ${TC}dry-run: would rebuild the initramfs presets.${NC}"
        return 0
    fi
    if ! command -v mkinitcpio >/dev/null 2>&1; then
        echo -e " ${TC}mkinitcpio is not installed. Nothing was refreshed.${NC}"
        return 1
    fi
    if ! ls "$PRESET_DIR"/*.preset >/dev/null 2>&1; then
        echo -e " ${TC}No mkinitcpio presets in $PRESET_DIR. Nothing was refreshed.${NC}"
        return 1
    fi
    if ! sudo mkinitcpio -P; then
        echo -e "$RED mkinitcpio failed. Check the output above and run: sudo mkinitcpio -P${NC}"
        return 1
    fi
    if ! ls "$BOOT_DIR"/initramfs-*.img >/dev/null 2>&1; then
        echo -e " ${TC}Warning: no initramfs images found in $BOOT_DIR after the rebuild.${NC}"
        return 1
    fi
    echo -e "$GREEN initramfs images rebuilt."
    return 0
}

# =======================
# Commands

function cmd_detect() {
    local gpus slot cls ven drv
    gpus=$(detect_gpus) || { echo -e "$NOPKGSMSG"; return 1; }
    while IFS='|' read -r slot cls ven drv; do
        [ -n "$slot" ] || continue
        echo "slot=$slot class=$cls vendor=$ven vendor_name=$(vendor_name "$ven") driver=$drv"
    done <<< "$gpus"
    return 0
}

function cmd_list() {
    local gpus slot cls ven drv pkgs kernelpkg
    echo -e "\n $BG$TC Hardware and Drivers (Arch) ${NC}"
    # One package with its version per line
    pkgs=$(pacman_query -Q 2>/dev/null | awk '$1 ~ /^(mesa|lib32-(mesa|nvidia-|vulkan-)|vulkan-|xf86-video-|nvidia-)/ {print $1 " " $2}')
    gpus=$(detect_gpus)
    if [ -z "$gpus" ]; then
        echo -e "$NOPKGSMSG"
    else
        while IFS='|' read -r slot cls ven drv; do
            [ -n "$slot" ] || continue
            echo -e "\n $TC$slot ${NC}- $(class_name "$cls")"
            echo "   vendor: $ven ($(vendor_name "$ven"))"
            if [ -n "$drv" ]; then
                echo "   kernel driver in use: $drv"
            else
                echo "   kernel driver in use: none"
            fi
        done <<< "$gpus"
        # One list for the whole system, not one per GPU
        echo -e "\n ${TC}driver packages installed${NC}"
        # One package per line, a long list would wrap
        if [ -z "$pkgs" ]; then
            echo "   none"
        else
            while IFS= read -r p; do
                [ -n "$p" ] && echo "   $p"
            done <<< "$pkgs"
        fi
    fi
    kernelpkg=$(running_kernel_package)
    echo -e "\n ${TC}Running kernel${NC}: $(running_version) ${kernelpkg:+(package: $kernelpkg)}"
    echo -e " ${TC}Installed kernels${NC}: $(installed_kernels | tr '\n' ' ')"
    echo -e " ${TC}Multilib repository${NC}: $(multilib_enabled && echo enabled || echo "disabled (32-bit driver packages are not available)")"
    echo ""
    return 0
}

function cmd_running_kernel() {
    running_kernel_package
    return 0
}

function cmd_running_flavour() {
    running_kernel_flavour
    return 0
}

function cmd_kernels() {
    local kernelpkg
    echo -e "\n ${TC}Installed kernels${NC}: $(installed_kernels | tr '\n' ' ')"
    echo -e " ${TC}Available kernels${NC}: $(available_kernels | tr '\n' ' ')"
    kernelpkg=$(running_kernel_package)
    echo -e " ${TC}Running kernel${NC}: $(running_version) ${kernelpkg:+(package: $kernelpkg)}"
    echo ""
    return 0
}

function cmd_installed_kernels() {
    installed_kernels
    return 0
}

function cmd_available_kernels() {
    available_kernels
    return 0
}

function cmd_install_kernel() {
    local pkgs="$*" p valid=""
    if [ -z "$pkgs" ]; then
        echo -e " Usage: archhw install-kernel <package> [...]"
        echo -e " Available kernels: $(available_kernels | tr '\n' ' ')"
        return 1
    fi
    # The available kernels come from a synced database
    require_synced_db || return 1
    for p in $pkgs; do
        # -F: a package name is a string, not a pattern
        if ! available_kernels | grep -qxF -- "$p"; then
            echo -e "$RED $p is not an available kernel package ${NC}"
            return 1
        fi
        valid="$valid $p"
    done
    guard_transaction || return 1
    confirm_install $valid || return 1
    echo ""
    run_root sudo pacman -Syu --noconfirm $valid || { echo -e "$RED Kernel installation failed ${NC}"; return 1; }
    if is_dry; then
        echo -e " ${TC}dry-run: nothing was installed.${NC}"
        bootloader_refresh
        return 0
    fi
    echo -e "$GREEN Kernel installed: $valid ${NC}"
    echo -e " For DKMS modules you may also want the matching headers package."
    bootloader_refresh
    return 0
}

function cmd_remove_kernel() {
    local pkgs="$*" p running runningflavour runningversion installed
    if [ -z "$pkgs" ]; then
        echo -e " Usage: archhw remove-kernel <package> [...]"
        echo -e " Installed kernels: $(installed_kernels | tr '\n' ' ')"
        return 1
    fi
    running=$(running_kernel_package)
    runningflavour=$(running_kernel_flavour)
    runningversion=$(running_version)
    installed=$(installed_kernels)
    for p in $pkgs; do
        if [ -n "$running" ] && [ "$p" == "$running" ]; then
            echo -e "$RED $p is the running kernel, removing it is refused ${NC}"
            return 1
        fi
        if [ "$p" == "$runningflavour" ]; then
            echo -e "$RED $p is the flavour of the running kernel, removing it is refused${NC}"
            echo -e " Running version: $runningversion"
            echo -e " It owns that kernel's /lib/modules and /boot files. Reboot onto another"
            echo -e " kernel first if you really want to remove it."
            return 1
        fi
        if ! echo "$installed" | grep -qxF -- "${p}"; then
            echo -e "$RED $p is not installed ${NC}"
            return 1
        fi
    done
    if [ "$(echo "$installed" | wc -w)" -le 1 ]; then
        echo -e "$RED This is the only installed kernel, removing it is refused ${NC}"
        return 1
    fi
    guard_transaction || return 1
    confirm_remove $pkgs || return 1
    echo ""
    # -R without -s: dependencies shared with other packages stay in place
    run_root sudo pacman -R --noconfirm $pkgs || { echo -e "$RED Kernel removal failed ${NC}"; return 1; }
    if is_dry; then
        echo -e " ${TC}dry-run: nothing was removed.${NC}"
        bootloader_refresh
        return 0
    fi
    echo -e "$GREEN Removed: $pkgs ${NC}"
    echo -e " Left-over packages can be checked with: pacman -Qdtq"
    bootloader_refresh
    return 0
}

function cmd_install_open() {
    local gpus pkgs="" p seen=""
    gpus=$(detect_gpus) || { echo -e "$NOPKGSMSG"; return 1; }
    while IFS='|' read -r slot cls ven drv; do
        case " $seen " in
        *" $ven "*) continue ;;
        esac
        seen="$seen $ven"
        for p in $(open_packages "$ven"); do
            pkgs="$pkgs $p"
        done
        if multilib_enabled; then
            for p in $(open_packages_32 "$ven"); do
                pkgs="$pkgs $p"
            done
        else
            echo -e "$MULTILIBMSG $PACMAN_CONF."
            echo -e "$MULTILIBHOW"
        fi
        echo -e " ${TC}GPU${NC}: $slot $(vendor_name "$ven")"
        [ "$ven" == "10de" ] && echo -e "$NONVIDIAFREE"
    done <<< "$gpus"
    pkgs=$(dedupe_pkgs $pkgs)
    [ -n "$pkgs" ] || { echo -e "$NOPKGSMSG"; return 1; }
    check_packages $pkgs || return 1
    guard_transaction || return 1
    confirm_install $pkgs || return 1
    echo ""
    run_root sudo pacman -Syu --noconfirm $pkgs || { echo -e "$RED Installation failed ${NC}"; return 1; }
    if is_dry; then
        echo -e " ${TC}dry-run: nothing was installed.${NC}"
        return 0
    fi
    echo -e "$GREEN Open source driver stack installed.${NC}"
    echo -e " Restart the graphical session to load it."
    return 0
}

function cmd_install_proprietary() {
    local gpus pkgs="" p seen="" base hdr
    require_synced_db || return 1
    gpus=$(detect_gpus) || { echo -e "$NOPKGSMSG"; return 1; }
    while IFS='|' read -r slot cls ven drv; do
        case " $seen " in
        *" $ven "*) continue ;;
        esac
        seen="$seen $ven"
        echo -e " ${TC}GPU${NC}: $slot $(vendor_name "$ven")"
        if [ "$ven" != "10de" ]; then
            echo -e " $(vendor_name "$ven") has no proprietary driver in the repositories."
            echo -e " The open source driver is the supported one."
            continue
        fi
        base=$(proprietary_base "$ven")
        for p in $(proprietary_packages "$ven"); do
            pkgs="$pkgs $p"
        done
        if multilib_enabled; then
            pkgs="$pkgs $NVIDIA_32"
        else
            echo -e " $NVIDIA_32 is skipped: [multilib] is not enabled in $PACMAN_CONF."
            echo -e "$MULTILIBHOW"
        fi
        echo -e " nvidia-open needs an NVIDIA Turing (2018) or newer card. Older cards have"
        echo -e " no driver package in the repositories anymore; use the open source"
        echo -e " driver (nouveau) instead."
        hdr=$(proprietary_headers "$base")
        if [ "$base" == "nvidia-open-dkms" ] && [ -z "$hdr" ]; then
            # A DKMS module without kernel headers cannot build
            echo -e "$RED The DKMS driver needs the headers of the running kernel and no "
            echo -e " <kernel-package>-headers package was found. Nothing was installed. ${NC}"
            echo -e " Arch names them linux-headers; a distro with versioned kernels names them"
            echo -e " after the kernel package (for example linux73-headers)."
            return 1
        fi
        if [ -n "$hdr" ]; then
            echo -e " The DKMS variant is used, so its headers are added: ${TC}${hdr}${NC}"
            pkgs="$pkgs $hdr"
        fi
    done <<< "$gpus"
    pkgs=$(dedupe_pkgs $pkgs)
    [ -n "$pkgs" ] || { echo -e " Nothing to do: no NVIDIA device detected.${NC}"; return 1; }
    check_packages $pkgs || return 1
    guard_transaction || return 1
    confirm_install $pkgs || return 1
    echo ""
    run_root sudo pacman -Syu --noconfirm $pkgs || { echo -e "$RED Installation failed ${NC}"; return 1; }
    if is_dry; then
        echo -e " ${TC}dry-run: nothing was installed.${NC}"
        return 0
    fi
    echo -e "$GREEN Proprietary driver installed.${NC}"
    echo -e " Log out and back in (or reboot) to load it."
    return 0
}

function usage() {
    echo " archhw - Arch-native hardware, driver and kernel helper"
    echo ""
    echo " Commands:"
    echo "   detect                 PCI display devices: slot, class, vendor, driver"
    echo "   list                   drivers in use, driver packages, kernels"
    echo "   kernels                installed and available kernel packages"
    echo "   installed-kernels      installed kernel package names, one per line"
    echo "   available-kernels      kernel package names in the repos, one per line"
    echo "   running-kernel         package of the running kernel (empty if unknown)"
    echo "   running-flavour        flavour of the running kernel, never empty"
    echo "   refresh-grub           regenerate grub.cfg with backup, verify, restore"
    echo "   install-kernel <pkg>   install kernel package(s)"
    echo "   remove-kernel <pkg>    remove kernel package(s), never the running one"
    echo "   install-open           open source graphics stack for the detected GPUs"
    echo "   install-proprietary    proprietary driver for the GPUs (NVIDIA only)"
    echo ""
    echo " Options:"
    echo "   --dry-run   show the root commands instead of running them"
    echo "   --yes       skip the confirmation prompt"
    echo ""
    echo " pacman.conf is never written: archhw reads it and names the 32-bit packages"
    echo " it skips while [multilib] is disabled; enable that repository yourself."
    echo ""
    echo " Environment overrides, each name replaces the path it names:"
    echo "   BMENU_PCI_ROOT, BMENU_PACMAN_CONF, BMENU_PACMAN_SYNC_DIR, BMENU_BOOT_DIR,"
    echo "   BMENU_PACMAN_DB_DIR, BMENU_MKINITCPIO_PRESET_DIR, BMENU_UNAME_R"
}

# =======================
# Argument parsing

COMMAND=""
while [ $# -gt 0 ]; do
    case "$1" in
    --dry-run)
        DRYRUN=1
        ;;
    --yes)
        ASSUME_YES=1
        ;;
    -h | --help)
        usage
        exit 0
        ;;
    -*)
        echo -e "$ERRORMSG ($1)"
        usage
        exit 2
        ;;
    *)
        if [ -z "$COMMAND" ]; then
            COMMAND="$1"
        else
            COMMAND_ARGS="$COMMAND_ARGS $1"
        fi
        ;;
    esac
    shift
done

case "$COMMAND" in
detect)
    cmd_detect
    ;;
list)
    cmd_list
    ;;
kernels)
    cmd_kernels
    ;;
installed-kernels)
    cmd_installed_kernels
    ;;
available-kernels)
    cmd_available_kernels
    ;;
running-kernel)
    cmd_running_kernel
    ;;
running-flavour)
    cmd_running_flavour
    ;;
refresh-grub)
    refresh_grub
    ;;
install-kernel)
    cmd_install_kernel $COMMAND_ARGS
    ;;
remove-kernel)
    cmd_remove_kernel $COMMAND_ARGS
    ;;
install-open)
    cmd_install_open
    ;;
install-proprietary)
    cmd_install_proprietary
    ;;
"")
    cmd_list
    ;;
*)
    echo -e "$ERRORMSG"
    echo -e "$TRYAGAINMSG"
    usage
    exit 2
    ;;
esac
exit $?
