#!/usr/bin/env bash
# Full system update (repo + AUR) inside the eww Updates panel — no terminal.
# sudo auth via a zenity GUI password dialog; paru output streamed to eww vars:
#   upd-running   true while the update runs (panel swaps button → progress)
#   upd-progress  the latest output line
set -u
EWW(){ eww update "$@" 2>/dev/null; }
CACHE="$HOME/.cache/eww"; mkdir -p "$CACHE"
ASK="$CACHE/askpass.sh"
cat > "$ASK" <<'EOF'
#!/bin/sh
zenity --password --title="System-Update" --width=340 2>/dev/null
EOF
chmod +x "$ASK"

EWW upd-running=true upd-progress="Authentifiziere…"

# --sudoloop keeps the sudo timestamp warm after the single askpass prompt, so the
# AUR build steps (makepkg → sudo pacman) never re-prompt on a missing tty.
SUDO_ASKPASS="$ASK" stdbuf -oL paru -Syu --noconfirm --skipreview --sudoloop --sudoflags -A 2>&1 \
  | while IFS= read -r line; do [ -n "$line" ] && EWW upd-progress="$line"; done
rc=${PIPESTATUS[0]}

if [ "$rc" -eq 0 ]; then EWW upd-progress="✓ System aktuell"; else EWW upd-progress="✗ Fehlgeschlagen (Code $rc)"; fi
EWW updates-list="$("$HOME/.config/eww/scripts/updates.sh" list)"
sleep 3
EWW upd-running=false upd-progress=""
