#!/bin/bash
# ============================================================
#  FWS Linux — fws-installer
#  Script de lancement de Calamares
# ============================================================

set -euo pipefail

# Vérifie que Calamares est installé
if ! command -v calamares >/dev/null 2>&1; then
    echo "ERREUR : calamares n'est pas installé."
    exit 1
fi

# Vérifie qu'on tourne bien en live
if [ ! -d /run/archiso ]; then
    echo "ATTENTION : Ce script doit être lancé depuis le live FWS."
fi

choose_desktop() {
    local selection

    if command -v zenity >/dev/null 2>&1; then
        selection=$(zenity --list \
            --title="Choix de l'environnement" \
            --width=520 \
            --height=320 \
            --radiolist \
            --print-column=2 \
            --column="Choisir" --column="Environnement" --column="Description" \
            TRUE "xfce" "Léger et classique" \
            FALSE "kde" "KDE Plasma" \
            FALSE "gnome" "GNOME" \
            FALSE "hyprland" "Wayland / Hyprland" \
            --text="Sélectionne l'environnement desktop à installer") || exit 1

        printf '%s' "$selection"
        return 0
    fi

    printf 'xfce'
}

DESKTOP="${FWS_DESKTOP:-xfce}"
DESKTOP_EXPLICIT=0
CALAMARES_ARGS=()

while [ "$#" -gt 0 ]; do
    case "$1" in
        -d|--desktop)
            shift
            DESKTOP="${1:-xfce}"
            DESKTOP_EXPLICIT=1
            ;;
        --desktop=*)
            DESKTOP="${1#*=}"
            DESKTOP_EXPLICIT=1
            ;;
        *)
            CALAMARES_ARGS+=("$1")
            ;;
    esac
    shift || true
done

if [ "$DESKTOP_EXPLICIT" -eq 0 ] && [ -z "${FWS_DESKTOP:-}" ]; then
    DESKTOP="$(choose_desktop)"
fi

case "$DESKTOP" in
    xfce|kde|gnome|hyprland)
        export FWS_DESKTOP="$DESKTOP"
        ;;
    *)
        echo "Environnement invalide: $DESKTOP"
        exit 1
        ;;
esac

# Lance Calamares avec les droits root
# -D6 active les logs de debug (retirer en production)
if [ "$EUID" -ne 0 ]; then
    if command -v sudo >/dev/null 2>&1; then
        # Persist the chosen desktop for Calamares (read by shellprocess before chroot)
        if [ -n "${FWS_DESKTOP:-}" ]; then
            mkdir -p /run
            printf '%s' "$FWS_DESKTOP" > /run/fws-desktop
        fi
        exec sudo -E calamares "${CALAMARES_ARGS[@]}"
    elif command -v pkexec >/dev/null 2>&1; then
        if [ -n "${FWS_DESKTOP:-}" ]; then
            mkdir -p /run
            printf '%s' "$FWS_DESKTOP" > /run/fws-desktop
        fi
        exec pkexec calamares "${CALAMARES_ARGS[@]}"
    else
        echo "ERREUR : Impossible de lancer Calamares en tant que root (sudo/pkexec non trouvés)."
        exit 1
    fi
else
        if [ -n "${FWS_DESKTOP:-}" ]; then
            mkdir -p /run
            printf '%s' "$FWS_DESKTOP" > /run/fws-desktop
        fi
        exec calamares "${CALAMARES_ARGS[@]}"
fi

