#!/bin/bash
# Généré par l'installateur FWS — (ré)installe le bureau « hyprland ».
# Usage : fws-desktop-retry [--auto]   (--auto = relancé par le service au 1er démarrage)
set -u
[ "$(id -u)" -eq 0 ] || exec sudo "$0" "$@"
AUTO=""
[ "${1:-}" = "--auto" ] && AUTO=1
if [ -n "$AUTO" ]; then
    wall "FWS : installation du bureau « hyprland » en cours… ne coupez pas l'alimentation." 2>/dev/null || true
fi
echo "==> Installation du bureau hyprland…"
# Keyring pacman : s'il est périmé, -Sy échoue alors que le réseau va bien
# (typique d'un système fraîchement installé depuis une image).
pacman-key --init            &>/dev/null || true
pacman-key --populate archlinux &>/dev/null || true
# Attente du réseau (DNS) : au 1er démarrage, NetworkManager peut mettre
# ~30 s à monter la connexion.
for _i in 1 2 3 4 5 6 7 8 9 10; do
    getent hosts geo.mirror.pkgbuild.com >/dev/null 2>&1 && break
    sleep 3
done
# Synchro + filtre : un paquet renommé/absent ne doit pas faire échouer TOUT
# le bureau (même approche que fws-setup-hardware pour la stack matérielle).
pacman -Syy --noconfirm || { echo "Échec de la synchro (réseau ?) — réessayez."; exit 1; }
_FILTERED=""
for _p in hyprland kitty wofi waybar sddm noto-fonts dolphin kio-extras udisks2 hyprlock grim slurp wl-clipboard playerctl mako libnotify polkit-gnome network-manager-applet xdg-desktop-portal-hyprland ttf-nerd-fonts-symbols pipewire pipewire-alsa pipewire-pulse wireplumber pavucontrol bluez bluez-utils blueman firefox python-gobject pacman-contrib; do
    pacman -Si "$_p" >/dev/null 2>&1 && _FILTERED="$_FILTERED $_p"
done
PKGS="${_FILTERED# }"
[ -n "$PKGS" ] || { echo "Aucun paquet du bureau hyprland trouvé dans les dépôts — réessayez plus tard."; exit 1; }
pacman -S --noconfirm --needed $PKGS || { echo "Échec (réseau ?) — réessayez."; exit 1; }
[ -n "sddm" ] && systemctl enable "sddm"
systemctl set-default graphical.target
rm -f /var/lib/fws/desktop-failed
[ -f /etc/motd ] && grep -q fws-desktop-retry /etc/motd && rm -f /etc/motd
echo "==> Bureau installé ✔"
if [ -n "$AUTO" ]; then
    echo "==> Passage sur l'écran de connexion…"
    systemctl isolate graphical.target || true
else
    echo "==> Redémarrez (reboot) pour arriver sur l'écran de connexion."
fi
