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

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

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

# Exit now if run as root (yay should be run as user)
assert-is-user

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

if [ ! -f "$PACKAGES_FILE" ]; then
  err "Package list not found at $PACKAGES_FILE"
  exit 1
fi

say "Starting local package cache process in $DEST_DIR"

# Create DEST_DIR
run sudo rm -rf "$DEST_DIR"
run sudo mkdir -p "$DEST_DIR"
run sudo chown 1000:1000 "$DEST_DIR"

# Loop over package names
for name in $(grep -v '^#' "$PACKAGES_FILE"); do
  say "Processing $(c "$name")..."

  # Use pacman for repo packages to avoid yay's 'install reason'
  if pacman -Si "$name" &>/dev/null; then
    run sudo pacman -Sw "$name" --cachedir "$DEST_DIR" --noconfirm --needed
  else
    # Fallback to yay for AUR packages
    run yay -Sw "$name" --cachedir "$DEST_DIR" --noconfirm --needed
  fi

  # Find the file just downloaded (latest version matching the name)
  file=$(sudo find "$DEST_DIR" -maxdepth 1 -name "${name}-*.pkg.tar.zst" -print | sort -V | tail -n 1)

  if [ -n "$file" ]; then
    # Determine the static target name
    target_name="$name"
    # Special case for blender as per your example
    [ "$name" == "blender-3.6-bin" ] && target_name="blender36"

    final_path="$DEST_DIR/${target_name}.pkg.tar.zst"

    if [ "$file" != "$final_path" ]; then
      say "Renaming to $(g "$target_name.pkg.tar.zst")"
      run sudo mv -f "$file" "$final_path"
    fi
  else
    err "Could not find downloaded file for $name"
  fi
done

# Cleanup signatures
say "Removing signature files..."
run sudo rm -f "$DEST_DIR"/*.sig

# Handle the mesa-current symlink
say "Ensuring mesa-current symlink..."
if [ -f "$DEST_DIR/mesa.pkg.tar.zst" ]; then
  (cd "$DEST_DIR" && run sudo ln -sf "mesa.pkg.tar.zst" "mesa-current.pkg.tar.zst")
fi

say "$(g "Done!") Local packages are ready in $DEST_DIR"
