#!/bin/bash
# GTK uses native Wayland input; forcing its toolkit module triggers Fcitx's startup diagnostic.
# X11 GTK reads gtk-im-module from settings.ini instead.
unset GTK_IM_MODULE
# Starchaser desktop session: what the login screen asks greetd to start after a successful login.
# greetd joins the session command's words with spaces and runs them through `sh -c` (no quoting), so the login
# screen passes just this path; everything that needs quoting lives here.
# Output goes to ~/.local/state/starchaser/session.log (previous run: session.log.1), since greetd discards it.
# A log that can't be written (a full disk, a folder owned by someone else) must never stop the login: a failed
# redirection on `exec` means the desktop never starts and greetd just shows the login screen again. So the log
# falls back to the session's runtime folder, and then to nowhere.
case "${1:-}" in
    -h|--help|help)     # answer before touching the log or starting anything
        echo "Usage: starchaser-session"; echo
        echo "Starts the Starchaser desktop. The login screen runs it after you sign in; there is no need to run it yourself."
        echo "Its messages go to ~/.local/state/starchaser/session.log."
        exit 0 ;;
esac
# An argument typed by a person in a terminal is refused before the log rotates or anything starts. From a login
# (greetd, autologin: no terminal) anything extra is ignored, never refused: a refusal there would mean a login
# that never starts a desktop.
if [ $# -gt 0 ] && [ -t 0 ]; then
    echo "starchaser-session: unexpected argument '$1' (it takes none)" >&2
    echo "Usage: starchaser-session" >&2
    exit 2
fi
L="$HOME/.local/state/starchaser/session.log"
mkdir -p "${L%/*}" 2>/dev/null
[ -f "$L" ] && mv -f "$L" "$L.1" 2>/dev/null
if ! { : > "$L"; } 2>/dev/null; then
    L=/dev/null
    if [ -n "$XDG_RUNTIME_DIR" ] && { : > "$XDG_RUNTIME_DIR/starchaser-session.log"; } 2>/dev/null; then
        L="$XDG_RUNTIME_DIR/starchaser-session.log"
    fi
fi
{
    echo "=== session start $(date)"
    env | grep -E '^(XDG_|WAYLAND|DISPLAY|HYPR|PATH=|SHELL|LANG)' | sort
} >> "$L" 2>&1
# Date & language: apply this account's formats to the desktop and every app it starts.
# Read assignments as data; never source or evaluate the settings file.
while IFS='=' read -r region_key region_value; do
    case "$region_key" in LANG|LC_TIME|LC_NUMERIC|LC_MONETARY|LC_MEASUREMENT)
        case "$region_value" in ''|*[!a-zA-Z0-9_.@-]*) continue ;; esac
        export "$region_key=$region_value" ;;
    esac
done < <(cat "${XDG_CONFIG_HOME:-$HOME/.config}/environment.d/30-starchaser-region.conf" 2>/dev/null)
# End Date & language.
# A new token for every login, even when logind keeps the user runtime directory alive.
# Terminals inherit it, so concurrent shells can claim the greeting without a per-terminal animation.
read -r STARCHASER_LOGIN_SESSION < /proc/sys/kernel/random/uuid
export STARCHASER_LOGIN_SESSION
# Include terminals launched through D-Bus or user services in the same login claim.
dbus-update-activation-environment --systemd STARCHASER_LOGIN_SESSION >> "$L" 2>&1 || true
export PATH="$HOME/.local/share/starchaser/ai-accounts/bin:$HOME/.local/bin:$PATH"
# Loading an input module starts its helper through D-Bus. Enable it only after a language was added.
if starchaser input method enabled 2>/dev/null; then
    export QT_IM_MODULE=fcitx XMODIFIERS=@im=fcitx
else
    unset QT_IM_MODULE GTK_IM_MODULE XMODIFIERS
fi

# Going back to a snapshot from before Get Starchaser's packages (an older Recovery, or a snapshot picked in the boot
# menu) takes /usr/share/starchaser away, but ~/.local/bin is outside snapshots and still links into it: Settings and
# every helper then stopped starting, with no message (QA 20261104-1542 005). Such a link goes back to this account's
# own copy of the same file, when there is one; every other link and file is left alone.
for link in "$HOME"/.local/bin/*; do
    [ -L "$link" ] && [ ! -e "$link" ] || continue
    target=$(readlink "$link")
    case "$target" in /usr/share/starchaser/*) ;; *) continue ;; esac
    own="$HOME/.local/share/starchaser/repo/${target#/usr/share/starchaser/}"
    [ -f "$own" ] && ln -sfn "$own" "$link" && echo "relinked ${link##*/} to this account's copy" >> "$L" 2>&1
done

# The first sign-in message on the session's console ($1): the screen cleared to the login screen's background, the
# words centered in its text color under "Starchaser" in its accent. Colors come from the login screen's theme copy
# (starchaser greeter sync), else Starchaser's dark defaults. The Linux console's palette is changed (ESC ] P n rrggbb:
# 0 is the background, 7 the text, 5 the accent, 4 the dimmer text) since it can't show other colors directly.
# The size is measured only AFTER the first write: on a fresh boot the framebuffer console takes the screen over at its
# first printed character and only then loads the big console font, so a size read before that is wrong (QA r30b: "50 160" read
# before, while the screen then drew 80x25 and the words landed cut off at the bottom right). banner_draw is run again
# by the dots loop whenever the size changes, so a font that loads late still ends up with the words centered.
first_signin_banner() {
    local t=$1 c
    BANNER_BG=0d0b1a BANNER_FG=e6e1ff BANNER_AC=9d7cff BANNER_DIM=c9c3e6
    c=$(python3 -c 'import json,sys
try: c=json.load(open("/var/lib/starchaser/greeter/theme.json")).get("colors") or {}
except Exception: c={}
for k in ("bg","text","accent","subtext"):
    v=str(c.get(k,"")).lstrip("#")
    print(v if len(v)==6 and all(x in "0123456789abcdefABCDEF" for x in v) else "-")' 2>/dev/null)
    if [ -n "$c" ]; then
        # unquoted on purpose: the four values, one per line, become $1..$4
        set -- $c
        [ "${1:--}" != - ] && BANNER_BG=$1; [ "${2:--}" != - ] && BANNER_FG=$2
        [ "${3:--}" != - ] && BANNER_AC=$3; [ "${4:--}" != - ] && BANNER_DIM=$4
    fi
    # not taken over yet: only the placeholder console is bound (no "frame buffer device" in vtconsole)
    local pending=no before sz
    grep -qs "frame buffer" /sys/class/vtconsole/vtcon*/name || pending=yes
    before=$(stty size 2>/dev/null < "$t")
    # colors, hidden cursor and a cleared screen first, then one dot in the background color: a printed character is
    # what makes the console take the screen over (escape codes and blanks don't count), and it can't be seen
    printf '\033]P0%s\033]P7%s\033]P5%s\033]P4%s\033[0;37;40m\033[?25l\033[H\033[2J\033[30m.\033[37m\033[H' \
        "$BANNER_BG" "$BANNER_FG" "$BANNER_AC" "$BANNER_DIM" > "$t"
    # the takeover and its font load finish just after: wait (up to 3 seconds) for the size to change
    if [ "$pending" = yes ]; then
        for _ in $(seq 30); do
            sleep 0.1
            sz=$(stty size 2>/dev/null < "$t")
            [ -n "$sz" ] && [ "$sz" != "$before" ] && break
        done
    fi
    banner_draw "$t"
}

# Draws (or redraws) the centered words for the console's size now; sets BANNER_SIZE and where the dots go.
banner_draw() {
    local t=$1 rows=25 cols=80 sz top x
    sz=$(stty size 2>/dev/null < "$t")
    case "$sz" in [0-9]*\ [0-9]*) rows=${sz% *}; cols=${sz#* } ;; esac
    [ "$rows" -ge 6 ] 2>/dev/null || rows=25; [ "$cols" -ge 20 ] 2>/dev/null || cols=80
    BANNER_SIZE="$rows $cols"
    local l1="Starchaser" l2="Setting up your desktop for the first time." l3="One moment..."
    [ "${#l2}" -gt "$cols" ] && l2="Setting up your desktop."
    top=$(( rows / 2 - 2 )); [ "$top" -lt 1 ] && top=1; [ $(( top + 4 )) -gt "$rows" ] && top=$(( rows - 4 ))
    BANNER_DOTS_ROW=$(( top + 4 )); BANNER_DOTS_COL=$(( (cols - 3) / 2 )); [ "$BANNER_DOTS_COL" -lt 0 ] && BANNER_DOTS_COL=0
    {
        printf '\033[0;37;40m\033[?25l\033[H\033[2J'
        x=$(( (cols - ${#l1}) / 2 + 1 )); [ "$x" -lt 1 ] && x=1
        printf '\033[%s;%sH\033[35m%s\033[37m' "$top" "$x" "$l1"
        x=$(( (cols - ${#l2}) / 2 + 1 )); [ "$x" -lt 1 ] && x=1
        printf '\033[%s;%sH%s' $(( top + 2 )) "$x" "$l2"
        x=$(( (cols - ${#l3}) / 2 + 1 )); [ "$x" -lt 1 ] && x=1
        printf '\033[%s;%sH\033[34m%s\033[37m' $(( top + 3 )) "$x" "$l3"
    } > "$t"
}

# A new account's first sign-in (decided 2026-10-08): Starchaser's per-user desktop setup first, so it gets the cockpit,
# the theme and the keys instead of a bare Hyprland with its own generated config. Also when an earlier first sign-in
# was cut short (the setup leaves its "pending" mark until it finishes). Accounts already set up have hyprland.lua and
# no mark: nothing runs. Its own account part only: no password, nothing system-wide. Whatever happens, the desktop
# still starts below.
if [ ! -e "$HOME/.config/hypr/hyprland.lua" ] || [ -e "$HOME/.local/state/starchaser/desktop-setup.pending" ]; then
    for r in "$HOME/.local/share/starchaser/repo" /usr/share/starchaser /usr/local/share/starchaser/repo; do
        [ -f "$r/installer/starchaser-desktop-setup.sh" ] && [ -f "$r/config/hypr/hyprland.lua" ] || continue
        echo "=== first sign-in: Starchaser desktop setup for this account (from $r)" >> "$L" 2>/dev/null
        # the screen is plain black for several seconds while this runs: say why on the console this session owns,
        # so it doesn't read as a crash (and the power button doesn't cut the setup short). Drawn in the login
        # screen's colors and centered, so it looks like the step between the login screen and the desktop, not a
        # different system's text console (QA r30). The console's palette is put back before the desktop starts.
        tty_out=""
        for t in /dev/tty "/dev/tty${XDG_VTNR:-}"; do
            [ "$t" = /dev/tty ] || [ -n "${XDG_VTNR:-}" ] || continue
            { : > "$t"; } 2>/dev/null && { tty_out=$t; break; }
        done
        dots_pid=""
        if [ -n "$tty_out" ]; then
            first_signin_banner "$tty_out" 2>/dev/null
            # a slow line of dots under the message: the setup is still working
            # (and the words drawn again for a console size that changed, e.g. a console font that loaded late)
            ( n=0; while sleep 1; do
                n=$(( n % 3 + 1 ))
                sz=$(stty size 2>/dev/null < "$tty_out")
                [ -n "$sz" ] && [ "$sz" != "$BANNER_SIZE" ] && banner_draw "$tty_out"
                # (the cursor hidden again each time: the console font loading late showed it again)
                printf '\033[?25l\033[%s;%sH\033[K%*s%s' "$BANNER_DOTS_ROW" 1 "$BANNER_DOTS_COL" "" "$(printf '%.*s' "$n" '...')" > "$tty_out" || exit
            done ) 2>/dev/null &
            dots_pid=$!
        fi
        if REPO="$r" STARCHASER_USER_ONLY=yes bash "$r/installer/starchaser-desktop-setup.sh" < /dev/null >> "$L" 2>&1; then
            echo "=== first sign-in setup finished" >> "$L" 2>/dev/null
        else
            echo "=== first sign-in setup didn't finish (exit $?); it runs again at the next sign-in" >> "$L" 2>/dev/null
        fi
        [ -n "$dots_pid" ] && kill "$dots_pid" 2>/dev/null
        # the console's own colors and cursor back (Linux console: ESC ] R resets the palette)
        [ -n "$tty_out" ] && { printf '\033]R\033[0m\033[?25h' > "$tty_out"; } 2>/dev/null
        break
    done
fi

# The greeter passes only a request for speech, after authentication. Save it as this account, then remove the
# one-login request so a later toggle-off stays off. The desktop's normal accessibility apply starts Orca.
if [ "${STARCHASER_LOGIN_SCREEN_READER:-}" = 1 ]; then
    starchaser accessibility login-speech >> "$L" 2>&1 || true
fi
unset STARCHASER_LOGIN_SCREEN_READER

# A move to Starchaser's system copy that was asked for while the desktop was running (starchaser defaults apply):
# done now, before anything reads the files it moves. Only when asked; whatever happens, the desktop still starts.
if [ -e "${XDG_STATE_HOME:-$HOME/.local/state}/starchaser/system-defaults.pending" ] && command -v starchaser >/dev/null 2>&1; then
    echo "=== moving to Starchaser's system copy (starchaser defaults apply --now)" >> "$L" 2>/dev/null
    timeout 120 starchaser defaults apply --now < /dev/null >> "$L" 2>&1 || echo "=== the move didn't finish (see above)" >> "$L" 2>/dev/null
fi
# The same move by itself after an update (decided 2026-11-02, #12), once per account and only for the groups whose
# move passed its test-VM checks: testing-channel computers first, the main channel once that version is promoted.
# A move that fails puts everything back. Its result is said once when the desktop is up, with Undo.
if command -v starchaser >/dev/null 2>&1; then
    timeout 120 starchaser defaults auto < /dev/null >> "$L" 2>&1 || echo "=== the move at sign-in didn't finish (see above)" >> "$L" 2>/dev/null
    if [ -e "${XDG_STATE_HOME:-$HOME/.local/state}/starchaser/system-defaults.notice" ]; then
        ( sleep 10; exec starchaser defaults notice ) < /dev/null >> "$L" 2>&1 &
    fi
fi

# A desktop that closes right after starting (start-hyprland already retries in safe mode, so this is the rare case of
# a desktop that can't start at all, e.g. no graphics driver) used to drop back to an empty login screen. Run it
# without exec, and on a quick failure leave a note the login screen reads ("<user> <seconds since 1970>"): in its
# shared folder when this account can write there, else in /tmp. A desktop that ran normally clears the note.
# greetd's signals are passed on, so ending the session from outside still ends the desktop.
NOTE=/var/lib/starchaser/greeter/session-failed
[ -w "${NOTE%/*}" ] || NOTE="/tmp/starchaser-session-failed-$USER"
start=$(date +%s)
printf '%s\n' "$start" > "${XDG_RUNTIME_DIR:-/run/user/$(id -u)}/starchaser-desktop-started"
# Every way to a screen in turn (the built-in graphics if chosen in Settings, Hyprland's own choice, each graphics
# device, safe graphics), each try logged here. start-hyprland itself exits 0 even when no graphics device works,
# so starchaser-display is what tells a desktop that started from one that couldn't (exit 3).
gpu_device=$(starchaser graphics device 2>> "$L") || gpu_device=
[[ $gpu_device =~ ^/dev/dri/card[0-9]+$ && -e $gpu_device ]] || gpu_device=
unset STARCHASER_BUILTIN_GRAPHICS
/usr/local/lib/starchaser/starchaser-display ${gpu_device:+--prefer "$gpu_device"} -- start-hyprland >> "$L" 2>&1 &
pid=$!
sig=0                                         # ended from outside: not a desktop that failed to start
trap 'sig=1; kill -TERM "$pid" 2>/dev/null' TERM INT
trap 'sig=1; kill -HUP "$pid" 2>/dev/null' HUP
status=0
while :; do
    wait "$pid"; status=$?
    kill -0 "$pid" 2>/dev/null || break       # wait returned for a signal while the desktop still runs: keep waiting
done
# Leaving normally or at the person's request is not a desktop that hung during startup.
finish_start_check() {
    if [ "$status" -eq 0 ] || [ "$sig" -ne 0 ]; then
        rm -f "${XDG_RUNTIME_DIR:-/run/user/$(id -u)}/starchaser-desktop-started"
    fi
}
finish_start_check
ran=$(( $(date +%s) - start ))
echo "=== logout desktop-exited $(date +%s%3N)" >> "$L" 2>/dev/null
# Satellites' session-end actions, after the desktop has closed: waited for (the runner stops each one after
# 5 seconds), so they finish before the login screen takes over. Nothing is run when no satellite has one.
if command -v starchaser >/dev/null 2>&1; then
    echo "=== logout session-end-start $(date +%s%3N)" >> "$L" 2>/dev/null
    timeout 10 starchaser satellite hook session-end --wait >> "$L" 2>&1 < /dev/null
    echo "=== logout session-end-finished $(date +%s%3N)" >> "$L" 2>/dev/null
fi
if [ "$status" -eq 3 ] && [ "$sig" = 0 ] && [ "${STARCHASER_TEXT_SIGNIN:-}" = 1 ]; then
    # signed in on the text console because no way to a screen worked: a text shell here, never a bare prompt
    echo "=== no way to a screen worked; a text session instead" >> "$L" 2>/dev/null
    rm -f "${XDG_RUNTIME_DIR:-/run/user/$(id -u)}/starchaser-desktop-started"
    printf '%s\n' "Starchaser: the desktop couldn't start on this computer's graphics (details: ~/.local/state/starchaser/session.log). This is a text session; type exit to sign out."
    exec "${SHELL:-/bin/bash}" -l
elif [ "$status" -ne 0 ] && [ "$ran" -lt 15 ] && [ "$sig" = 0 ]; then
    echo "=== the desktop closed after ${ran}s (exit $status)" >> "$L" 2>/dev/null
    { printf '%s %s\n' "$USER" "$(date +%s)" > "$NOTE"; } 2>/dev/null
elif [ -f "$NOTE" ] && [ -O "$NOTE" ]; then
    rm -f "$NOTE"
fi
echo "=== logout returning-to-greeter $(date +%s%3N)" >> "$L" 2>/dev/null
exit "$status"
