# Install AUR packages one at a time, so a single build failure (common with the
# AUR — removed packages, broken builds) doesn't abort the rest. yay still pulls
# each package's AUR dependencies automatically. Failures are collected and
# reported at the end, and logged to ~/aur-failed.log for retrying.
LOG="$HOME/aur-failed.log"
: > "$LOG"

# Keep sudo's credential cache warm for the whole AUR run. yay installs each
# built package via `sudo pacman`; a long compile can outlast sudo's default
# 15-minute timeout and trigger a password prompt mid-run. Authenticate once,
# then refresh the timestamp in the background (self-terminating if run.sh dies).
sudo -v || die "sudo authentication failed"
{ while true; do sudo -n true; sleep 60; kill -0 "$$" 2>/dev/null || exit; done; } &
sudo_keepalive=$!

while read -r pkg; do
  yay -S --needed --noconfirm "$pkg" || echo "$pkg" >> "$LOG"
done < <(grep -vE '^\s*#|^\s*$' "$REPO_ROOT/03-user/packages/aur.txt")

kill "$sudo_keepalive" 2>/dev/null || true   # stop the sudo refresher

if [ -s "$LOG" ]; then
  echo ""
  echo "!! $(wc -l < "$LOG") AUR package(s) FAILED — retry later with:"
  echo "     yay -S \$(cat $LOG)"
  echo "   failed:"
  sed 's/^/     - /' "$LOG"
else
  rm -f "$LOG"
  info "all AUR packages installed"
fi
