#!/bin/bash
# lightdm.sh — LightDM + GTK greeter (cyberqueer-themed)
#
# The default greeter for HyprLua. LightDM's GTK greeter reuses the cyberqueer
# GTK theme shipped in this repo (gtk-themes/cyberqueer), so it matches the rest
# of the desktop, and it is driven by a single trivial INI file
# (/etc/lightdm/lightdm-gtk-greeter.conf) — the simplest config of the
# LightDM/LXDM/GDM options.
#
# This module is self-contained (installs the theme + skull background itself)
# so it can also be selected on its own from modules.conf. It is mutually
# exclusive with the ly greeter module. Enabling LightDM here disables the other
# greeters (greetd, ly) and the tty1 getty so exactly one display manager runs.

set -euo pipefail
source "$(dirname "${BASH_SOURCE[0]}")/../../lib/logging.sh"

# apps/ → optional-Modules → modules → setup → repo root (four levels up).
DOTFILES_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/../../../.." && pwd)"

log "Installing LightDM + GTK greeter..."
sudo pacman -S --noconfirm --needed lightdm lightdm-gtk-greeter

# ── Ensure the cyberqueer GTK theme is present system-wide ────────────────────
# The greeter runs as the 'lightdm' user and reads themes from /usr/share/themes.
# DE modules already install this, but copy it here too so LightDM can be chosen
# standalone. (Papirus-Dark icons are pulled in by the desktop modules.)
GTK_THEME_SRC="$DOTFILES_DIR/gtk-themes/cyberqueer"
if [[ -d "$GTK_THEME_SRC" ]]; then
    log "Installing cyberqueer GTK theme to /usr/share/themes..."
    sudo cp -r "$GTK_THEME_SRC" /usr/share/themes/
else
    warn "cyberqueer GTK theme not found at $GTK_THEME_SRC — greeter will use the default GTK theme."
fi

# ── Render the skull background from the bundled SVG ───────────────────────────
# lightdm-gtk-greeter needs a raster background; convert the 1920x1080 SVG.
SKULL_SRC="$DOTFILES_DIR/resources/bg-skull.svg"
SKULL_DST="/usr/share/backgrounds/cyberqueer-skull.png"
if [[ -f "$SKULL_SRC" ]]; then
    if ! command -v rsvg-convert &>/dev/null; then
        log "Installing librsvg (rsvg-convert) for SVG→PNG conversion..."
        sudo pacman -S --noconfirm --needed librsvg
    fi
    log "Rendering skull background → $SKULL_DST..."
    TMP_BG="$(mktemp /tmp/lightdm-skull.XXXXXX.png)"
    trap 'rm -f "$TMP_BG"' EXIT
    rsvg-convert -w 1920 "$SKULL_SRC" -o "$TMP_BG"
    sudo install -Dm644 "$TMP_BG" "$SKULL_DST"
else
    warn "Skull SVG not found at $SKULL_SRC — greeter will fall back to a solid background."
fi

# ── Deploy the greeter configuration ──────────────────────────────────────────
GREETER_CONF_SRC="$DOTFILES_DIR/etc-lightdm/lightdm-gtk-greeter.conf"
if [[ -f "$GREETER_CONF_SRC" ]]; then
    log "Deploying lightdm-gtk-greeter.conf..."
    sudo install -Dm644 "$GREETER_CONF_SRC" /etc/lightdm/lightdm-gtk-greeter.conf
else
    warn "Greeter config not found at $GREETER_CONF_SRC — LightDM will use greeter defaults."
fi

# ── HiDPI + multi-monitor display setup ───────────────────────────────────────
# lightdm-gtk-greeter is an Xorg client; on a multi-monitor / HiDPI box X must be
# told to enable every output and scale up, or a monitor stays blank at the login
# screen and the greeter is tiny. display-setup.sh (root, before the greeter)
# handles both. Wire it into lightdm.conf's [Seat:*] idempotently.
DISPLAY_SETUP_SRC="$DOTFILES_DIR/etc-lightdm/display-setup.sh"
if [[ -f "$DISPLAY_SETUP_SRC" ]]; then
    log "Deploying greeter display-setup script..."
    sudo install -Dm755 "$DISPLAY_SETUP_SRC" /etc/lightdm/display-setup.sh
    # xrandr/xrdb are needed by the script at greeter time.
    sudo pacman -S --noconfirm --needed xorg-xrandr xorg-xrdb
    # Match only the real setting form (#display-setup-script=), never the
    # "# display-setup-script = <description>" documentation comment (note the
    # space after '#') — otherwise the doc line gets turned into a stray active
    # setting under [LightDM].
    if grep -qE '^\s*display-setup-script\s*=\s*/etc/lightdm/display-setup.sh' /etc/lightdm/lightdm.conf; then
        skip "display-setup-script already wired in lightdm.conf"
    elif grep -qE '^\s*#?display-setup-script\s*=' /etc/lightdm/lightdm.conf; then
        sudo sed -i -E 's|^\s*#?display-setup-script\s*=.*|display-setup-script=/etc/lightdm/display-setup.sh|' /etc/lightdm/lightdm.conf
        log "Wired display-setup-script into lightdm.conf"
    else
        sudo sed -i '/^\[Seat:\*\]/a display-setup-script=/etc/lightdm/display-setup.sh' /etc/lightdm/lightdm.conf
        log "Added display-setup-script to [Seat:*] in lightdm.conf"
    fi
else
    warn "display-setup.sh not found at $DISPLAY_SETUP_SRC — greeter monitors/scaling unmanaged."
fi

# ── FIDO / U2F login at the greeter ───────────────────────────────────────────
# LightDM's PAM stack only `include`s system-login, which has no pam_u2f — so
# hardware-key login (supported by the other greeters here) would not work. Add
# it, matching this machine's origin/appid (pam://$hostname, the pam_u2f default
# used at enrolment). `nouserok` lets users without an enrolled key still log in
# with their password alone.
PAM_LIGHTDM=/etc/pam.d/lightdm
if [[ -f "$PAM_LIGHTDM" ]] && ! grep -q pam_u2f "$PAM_LIGHTDM"; then
    U2F_HOST="$(hostnamectl --static hostname 2>/dev/null || hostname)"
    log "Enabling pam_u2f (FIDO) for the LightDM greeter..."
    sudo sed -i "/^auth\s\+include\s\+system-login/a auth        required    pam_u2f.so nouserok cue origin=pam://${U2F_HOST} appid=pam://${U2F_HOST}" "$PAM_LIGHTDM"
else
    skip "pam_u2f already present in $PAM_LIGHTDM (or file missing)"
fi

# ── Greeter background tracks the user's desktop wallpaper ─────────────────────
# The wallpaper picker writes ~/.config/hypr/usr/wallpaper.conf; a root .path unit
# copies the chosen wallpaper to a system path the greeter can read (the user's
# home is 0700). Install the helper + units with the target user substituted in.
TARGET_USER="${SUDO_USER:-$(id -un)}"
PREF_MON="${LIGHTDM_GREETER_MONITOR:-}"
WP_HELPER_SRC="$DOTFILES_DIR/etc-lightdm/lightdm-greeter-wallpaper"
if [[ -f "$WP_HELPER_SRC" ]]; then
    log "Installing greeter wallpaper-sync helper + units (user: $TARGET_USER)..."
    sudo install -Dm755 "$WP_HELPER_SRC" /usr/local/bin/lightdm-greeter-wallpaper
    for unit in lightdm-greeter-wallpaper.service lightdm-greeter-wallpaper.path; do
        tmp="$(mktemp)"
        sed -e "s|@USER@|${TARGET_USER}|g" -e "s|@PREFERRED_MONITOR@|${PREF_MON}|g" \
            "$DOTFILES_DIR/etc-lightdm/$unit" > "$tmp"
        sudo install -Dm644 "$tmp" "/etc/systemd/system/$unit"
        rm -f "$tmp"
    done
    sudo systemctl daemon-reload
    enable_service lightdm-greeter-wallpaper.path
    # Seed the greeter background now: user's current wallpaper if set, else skull.
    sudo PREFERRED_MONITOR="$PREF_MON" /usr/local/bin/lightdm-greeter-wallpaper "$TARGET_USER" || true
    if [[ ! -f /usr/share/backgrounds/lightdm-greeter-bg.png && -f "$SKULL_DST" ]]; then
        sudo install -Dm644 "$SKULL_DST" /usr/share/backgrounds/lightdm-greeter-bg.png
    fi
else
    warn "Wallpaper-sync helper not found — greeter background will not track the desktop wallpaper."
    [[ -f "$SKULL_DST" ]] && sudo install -Dm644 "$SKULL_DST" /usr/share/backgrounds/lightdm-greeter-bg.png
fi

# ── Make LightDM the sole display manager ─────────────────────────────────────
# LightDM manages its own VT; free tty1 and disable the competing greeters so
# nothing else races it.
sudo systemctl disable getty@tty1.service || true
disable_service greetd.service
disable_service ly@tty1.service
enable_service lightdm.service

log "LightDM installed and enabled. The cyberqueer GTK greeter starts on next boot."
