#!/bin/bash
# Update every out-of-date AUR package individually so a single broken build
# doesn't abort the entire upgrade run.  Failed packages are collected and
# reported at the end; the script exits 1 if any package failed.

# set -u: treat unset variables as errors to avoid silent empty-string expansion
set -u

# yay -Qua: list installed AUR packages that have an available update.
# awk '{print $1}' strips the version columns, leaving just the package names.
# mapfile -t reads those names into the indexed array pkgs (one entry per line).
mapfile -t pkgs < <(yay -Qua | awk '{print $1}')

if [ ${#pkgs[@]} -eq 0 ]; then
    echo "No AUR updates available."
    exit 0
fi

echo "Found ${#pkgs[@]} AUR package(s) with updates:"
printf '  %s\n' "${pkgs[@]}"
echo

# Accumulate failures so later packages still get a chance to update.
failed=()
for pkg in "${pkgs[@]}"; do
    echo "==> Updating $pkg"
    # -S <pkg>          : install/upgrade the specific package (not all AUR)
    # --answerdiff None : skip PKGBUILD diff review (non-interactive)
    # --answerclean All : always clean the build directory before compiling
    # --removemake      : remove make-only deps after the build (keeps system lean)
    if yay -S --noconfirm --answerdiff None --answerclean All --removemake "$pkg"; then
        echo "==> $pkg: OK"
    else
        echo "==> $pkg: FAILED"
        failed+=("$pkg")
    fi
    echo
done

# Report any failures and signal a non-zero exit so callers can react.
if [ ${#failed[@]} -gt 0 ]; then
    echo "Failed packages:"
    printf '  %s\n' "${failed[@]}"
    exit 1
fi
