#!/usr/bin/env bash
# vim:et:ts=2:sts=2:sw=2

# Get absolute repository root (especially when symlinked)
ROOT="$(realpath "$(dirname "$(dirname "$(readlink -f "${BASH_SOURCE[0]}")")")")"

# Load accompanying bash library
source "$ROOT/lib/lib.bash"

# Exit now if run as root user
assert-is-user

DEST_DIR="/usr/local/src"
PACKAGES_LIST="$ROOT/roles/desktop/packages.txt"
TMP_CACHE_DIR=""

cleanup() {
  if [ -n "$TMP_CACHE_DIR" ] && [ -d "$TMP_CACHE_DIR" ]; then
    run rm -rf "$TMP_CACHE_DIR"
  fi
}
trap cleanup EXIT

if [ "$1" = "-h" ] || [ "$1" = "--help" ]; then
  say "
  USAGE:
    $(g "${BASH_SOURCE##*/}")

  DESCRIPTION:
    Downloads packages listed in $(c "$PACKAGES_LIST") using pacman -Sw
    into a temporary cache, then copies them to $(c "$DEST_DIR").
    It also ensures the $(c mesa-current.pkg.tar.zst) symlink is correctly set.
    Signature files (.sig) are removed after download.
"
  exit 1
fi

say "Preparing to download local packages for hacks."
if [ ! -f "$PACKAGES_LIST" ]; then
  err "Package list $(c "$PACKAGES_LIST") not found. Refusing to continue."
  exit 1
fi

readarray -t PACKAGES < <(grep -v '^[[:space:]]*#' "$PACKAGES_LIST" | grep -v '^[[:space:]]*$')

if [ ${#PACKAGES[@]} -eq 0 ]; then
  err "No packages found in $(c "$PACKAGES_LIST"). Refusing to continue."
  exit 1
fi

say "Found $(c ${#PACKAGES[@]}) packages to download."

TMP_CACHE_DIR=$(mktemp -d)
say "Using temporary cache directory: $(c "$TMP_CACHE_DIR")"

say "Downloading packages using pacman -Sw..."
# --noconfirm: Assume yes to prompts
# --needed: Only download if not already installed (though cache dir is empty)
if ! sudo pacman -Sw --cachedir "$TMP_CACHE_DIR" --noconfirm --needed "${PACKAGES[@]}"; then
  err "Failed to download packages with pacman -Sw."
  exit 1
fi

# Get the exact paths of the downloaded package files from the cache
# pacman -Swp outputs paths like "file:///path/to/package.pkg.tar.zst"
mapfile -t DOWNLOADED_PKG_FILES < <(
  pacman -Swp --cachedir "$TMP_CACHE_DIR" --noconfirm --needed "${PACKAGES[@]}" | sed 's|^file://||'
)

if [ ${#DOWNLOADED_PKG_FILES[@]} -eq 0 ]; then
  err "No packages were found in the temporary cache after pacman -Sw. This is unexpected."
  exit 1
fi

say "Copying downloaded packages to $(c "$DEST_DIR")..."
run sudo mkdir -p "$DEST_DIR"
run sudo chown admin:admin "$DEST_DIR"

for pkg_file in "${DOWNLOADED_PKG_FILES[@]}"; do
  if [ -f "$pkg_file" ]; then
    say "  Copying $(c "$(basename "$pkg_file")")"
    run sudo cp -v "$pkg_file" "$DEST_DIR/"
  else
    warn "  Expected package file $(c "$pkg_file") not found in cache. Skipping."
  fi
done

say "Ensuring symlink $(c "mesa-current.pkg.tar.zst") -> $(c "mesa.pkg.tar.zst") in $(c "$DEST_DIR")"
if [ -e "$DEST_DIR/mesa.pkg.tar.zst" ]; then
  (cd "$DEST_DIR" && sudo ln -sf "mesa.pkg.tar.zst" "mesa-current.pkg.tar.zst")
else
  warn "Target for mesa symlink $(c "mesa.pkg.tar.zst") not found in $(c "$DEST_DIR"). Symlink not created."
  warn "Please ensure 'mesa' package was downloaded and is named correctly."
fi

say "$(g "Success!") Local packages are ready in $(c "$DEST_DIR")."
