#!/bin/bash
# ╔══════════════════════════════════════════════════════════════════════════════╗
# ║  setup/modules/core-packages.sh — Core system package installation        ║
# ║                                                                              ║
# ║  PURPOSE:                                                                    ║
# ║    Installs all base-layer packages that every configuration of this        ║
# ║    system relies on. This is the largest and most time-consuming module.   ║
# ║                                                                              ║
# ║  WHEN TO RUN:                                                                ║
# ║    After package-managers.sh (yay must be present for the AUR packages).   ║
# ║    Called "core" in the TUI installer's component checklist.               ║
# ║                                                                              ║
# ║  CATEGORIES INSTALLED:                                                       ║
# ║    - Archiving & file utilities (7zip, atool, dust, fd, fzf, ripgrep)     ║
# ║    - Base build tools (base-devel, gcc, rust, rustup, python, ruby)       ║
# ║    - Networking (networkmanager, iwd, openssh, wpa_supplicant, bind, ldns) ║
# ║    - Audio (pipewire, wireplumber, libpulse)                               ║
# ║    - Boot & storage (grub, btrfs-progs, dosfstools, udisks2, udiskie)     ║
# ║    - Terminal utilities (btop, htop, tmux, mc, yazi, nano, vim, neovim)   ║
# ║    - System monitoring (fastfetch, lshw, lsof, smartmontools, vnstat)      ║
# ║    - Security (fail2ban, ufw, pciutils, usbutils)                          ║
# ║    - Misc: flatpak, distrobox, qrencode, fdupes, lynx, tldr, tree         ║
# ╚══════════════════════════════════════════════════════════════════════════════╝

set -euo pipefail
# -e: exit immediately if any package install fails
# -u: error on unset variables
# -o pipefail: catch failures inside pipes

# Load shared logging helpers (log, skip, warn, err functions)
source "$(dirname "${BASH_SOURCE[0]}")/lib/logging.sh"

log "Installing core packages..."

# Single pacman invocation for efficiency:
#   -S: sync (install)
#   -yu: update the package database and upgrade existing packages first
#   --noconfirm: don't prompt for confirmation (needed for scripted install)
#   --needed: skip packages that are already up-to-date (idempotency)
#
# Package groupings with rationale:

# Packages are collected in an array rather than written as a single
# backslash-continued `pacman` invocation: an array literal is the only form
# where `#` comments (both full-line and trailing) are allowed between items.
# A continued command would treat the first inline comment as the end of the
# command, silently dropping every package after it.
CORE_PACKAGES=(
    # ── Archiving & file utilities ────────────────────────────────────────────
    7zip                  # Modern replacement for p7zip — handles .7z, .zip, .rar, etc.
    arch-install-scripts  # genfstab and other Arch install helpers (useful even post-install)
    atftp                 # TFTP client/server — used by some network boot tools
    atool                 # Universal archive wrapper (handles zip/tar/gz/xz with one command)

    # ── Base system & build tools ─────────────────────────────────────────────
    base                  # Minimal Arch base (filesystem, bash, glibc, etc.)
    base-devel            # AUR build requirements: make, gcc, binutils, pkg-config, etc.
    bc                    # Arbitrary precision calculator — used in many shell scripts
    bind                  # DNS tools: dig, nslookup, host
    bluez                 # Bluetooth protocol stack — enables BT devices
    btrfs-progs           # btrfs filesystem tools: mkfs.btrfs, btrfsck, snapper
    btop                  # Interactive resource monitor (CPU/mem/net/disk)

    cronie                # Cron daemon for scheduled tasks (enabled later in core.sh)
    curl                  # HTTP/FTP transfer tool — used by many installers

    # ── Hardware & disk utilities ─────────────────────────────────────────────
    dmidecode             # Reads hardware info from DMI/SMBIOS (CPU, memory, BIOS)
    distrobox             # Run other distro containers inside Arch (uses podman/docker)
    dosfstools            # mkfs.fat for FAT/EFI partitions; used when setting up boot
    dust                  # Disk usage analyzer — like `du` but cleaner output

    # ── Filesystem & recovery ────────────────────────────────────────────────
    e2fsprogs             # ext4 filesystem tools: fsck.ext4, mkfs.ext4, tune2fs
    fail2ban              # Bans IPs after repeated auth failures (SSH protection)
    fastfetch             # System info display (neofetch replacement, faster)
    fd                    # Fast alternative to `find`, respects .gitignore
    fdupes                # Find duplicate files by checksum
    ffmpeg                # Video/audio processing framework; required by many tools
    firefox               # Default browser (also in DE install, but needed as base)
    flatpak               # Universal app sandbox format; Flathub remote added in pkg-mgr
    fzf                   # Fuzzy finder — used by shell, yazi, neovim integrations

    # ── Compilers & language runtimes ────────────────────────────────────────
    gcc                   # GNU C compiler — needed for native AUR builds
    git                   # Version control — required everywhere
    glib2                 # GNOME low-level lib; used by many GTK/D-Bus tools
    greetd-tuigreet       # Text-mode login greeter (configured in core.sh)
    grub                  # GRUB2 bootloader for x86_64-efi

    # ── Hardware identification & networking ──────────────────────────────────
    hdparm                # Disk performance testing and low-level ATA control
    htop                  # Interactive process viewer (classic alternative to btop)
    inetutils             # hostname, telnet, rsh, ftp utilities
    iputils               # ping, tracepath, arping — basic IP network tools
    iwd                   # Intel Wireless Daemon — WiFi backend for NetworkManager
    jq                    # JSON processor — used by installer scripts and modules
    ldns                  # DNS library + drill tool (alternative to dig)
    less                  # Pager for viewing long output; also needed by man
    libpulse              # PulseAudio client library — compatibility shim for pipewire
    linux                 # The Linux kernel itself
    linux-firmware        # Microcode and firmware blobs for hardware support
    lshw                  # Detailed hardware listing (CPU, memory, PCI devices)
    lsof                  # List open files — invaluable for debugging processes/sockets

    lynx                  # Text-mode web browser — useful in TTY-only environments

    # ── Editors & documentation ──────────────────────────────────────────────
    man-db                # Man page database and viewer
    mc                    # Midnight Commander — two-pane terminal file manager
    nano                  # Simple terminal text editor for quick edits
    neovim                # Primary editor (configured via dotfiles/nvim/)
    networkmanager        # Network connection manager daemon

    # ── Fetch & monitoring ────────────────────────────────────────────────────
    onefetch              # Git repo summary in the terminal (like neofetch for repos)
    openbsd-netcat        # Netcat implementation — port scanning, simple TCP connections
    openssh               # SSH client and server (sshd enabled in optional module)
    parted                # Disk partitioning tool — used by arch-autoinstall.sh
    pciutils              # lspci — list PCI devices (needed for GPU detection)
    pipewire              # Modern audio/video server (replaces PulseAudio + JACK)
    # Install the PipeWire JACK/Pulse/ALSA shims explicitly so PipeWire is the
    # chosen provider for the virtual `jack`/`pulse` packages. Otherwise a
    # jack-dependent package here (e.g. ffmpeg) makes pacman pick jack2 by default,
    # which later conflicts with the DE modules' pipewire-jack and aborts them.
    pipewire-jack         # JACK API provided by PipeWire (conflicts with jack2)
    pipewire-pulse        # PulseAudio server replacement via PipeWire
    pipewire-alsa         # ALSA → PipeWire routing (config, no conflicting daemon)

    # ── Programming languages ────────────────────────────────────────────────
    python                # Python 3 interpreter
    python-pip            # Python package manager
    qrencode              # Generate QR codes in terminal — useful for sharing WiFi/URLs
    ripgrep               # Fast recursive grep replacement (rg command)
    rsync                 # Efficient file sync over SSH or locally
    ruby-pkg-config       # Ruby gem build helper — needed by some AUR packages
    # NOTE: do NOT add the `rust` package here — it conflicts with `rustup` (both
    # provide cargo/rustc), and pacman --noconfirm cannot resolve the conflict, so
    # it aborts the ENTIRE core-packages transaction. We use rustup exclusively
    # (`rustup default stable` in package-managers/shell-setup/DE modules).
    rustup                # Rust toolchain manager — provides rustc/cargo via toolchains

    # ── System monitoring & debugging ────────────────────────────────────────
    smartmontools         # S.M.A.R.T. disk health monitoring (smartctl)
    strace                # System call tracer — debugging tool for process behavior
    symlinks              # Scans and optionally fixes broken symlinks
    sysstat               # System performance stats: iostat, mpstat, pidstat, sar
    tldr                  # Simplified man pages with practical examples
    tmux                  # Terminal multiplexer — persistent sessions over SSH
    tree                  # Display directory structure as a tree

    # ── Disk & USB management ────────────────────────────────────────────────
    udisks2               # D-Bus service for auto-mounting removable media
    udisks2-btrfs         # btrfs extension for udisks2
    udiskie               # User-space udisks2 automounter daemon
    ufw                   # Uncomplicated Firewall — iptables frontend
    usbutils              # lsusb — list USB devices

    # ── Network tools & misc ─────────────────────────────────────────────────
    vim                   # Classic Vi IMproved editor (backup editor, always present)
    vnstat                # Network traffic monitor — tracks usage per interface
    wget                  # HTTP/FTP file downloader
    whois                 # Domain name lookup tool
    wireplumber           # Session/policy manager for PipeWire (required for audio)
    wireless_tools        # Legacy iwconfig, iwlist — sometimes needed for troubleshooting
    wpa_supplicant        # WPA2/WPA3 supplicant for WiFi authentication
    # NOTE: wprs is NOT in the official repos (AUR: wprs-git). It must never be
    # listed here — pacman aborts the ENTIRE transaction on an unknown target, so
    # one AUR entry would prevent every core package (wget, etc.) from installing.
    # Install it via the optional wprs.sh module (which uses yay) instead.

    # ── File manager & archive ────────────────────────────────────────────────
    yazi                  # Terminal file manager with image preview and fuzzy search
    zip                   # Create ZIP archives
    unzip                 # Extract ZIP archives
    zram-generator        # Systemd-based zram compressed swap setup (improves RAM efficiency)
)

sudo pacman -Syu --noconfirm --needed -- "${CORE_PACKAGES[@]}"

# ── AUR packages ──────────────────────────────────────────────────────────────
# Only install packages that are NOT available in official repos.
# pamtester: PAM module tester — used to verify FIDO2/U2F PAM stack without logging out.
#   Available only in AUR because it's a small utility not deemed mainline-worthy.
log "Installing AUR packages..."
yay -S --aur --noconfirm --needed pamtester

log "Core packages installed."
