#!/bin/bash
# gnucego-fix-autologin.sh — remove o autologin (live) do display manager no
# pós-instalação do Calamares, para o usuário/senha funcionar após instalar.
# Detecta GDM (GNOME) ou LightDM (MATE/Cinnamon/i3wm/XFCE), CADA UM
# independentemente (evita pular o LightDM quando o GDM já foi tratado).
# Copyright (C) 2026 GNUcego contributors — GPLv3+
set -e

C="$1"
[ -d "$C" ] || { echo "uso: $0 <chroot>"; exit 1; }

SP="$C/etc/calamares/modules/shellprocess.conf"
[ -f "$SP" ] || { echo "sem shellprocess.conf"; exit 1; }

# construir as linhas de remoção de autologin, verificando CADA DM em separado
add_lines=""
if [ -f "$C/etc/gdm3/daemon.conf" ] && ! grep -q "AutomaticLoginEnable" "$SP"; then
    add_lines="$add_lines
  - \"sed -i '/AutomaticLoginEnable/d' /etc/gdm3/daemon.conf\"
  - \"sed -i '/AutomaticLogin=/d' /etc/gdm3/daemon.conf\""
fi
if [ -f "$C/etc/lightdm/lightdm.conf" ] && ! grep -q "autologin-user=" "$SP"; then
    add_lines="$add_lines
  - \"sed -i '/autologin-user=/d' /etc/lightdm/lightdm.conf\"
  - \"sed -i '/autologin-session=/d' /etc/lightdm/lightdm.conf\""
fi

[ -z "$add_lines" ] && { echo "autologin já tratado (ou sem DM detectado)"; exit 0; }

# inserir antes do update-desktop-database
if grep -q "update-desktop-database" "$SP"; then
    python3 - "$SP" "$add_lines" <<'PYEOF'
import sys
p, add = sys.argv[1], sys.argv[2]
txt = open(p).read()
anchor = '  - "update-desktop-database'
if anchor in txt:
    txt = txt.replace(anchor, add.strip("\n") + "\n" + anchor, 1)
else:
    txt = txt.rstrip() + "\n" + add + "\n"
open(p, 'w').write(txt)
print("  autologin removido no shellprocess")
PYEOF
else
    printf '%s\n' "$add_lines" >> "$SP"
    echo "  autologin removido no shellprocess (append)"
fi

echo "CONCLUÍDO: $(basename $C)"
