#!/bin/sh
# SPDX-License-Identifier: MIT
# Copyright (C) 2026 pake <pake@fedora.tw> - https://pomelo-os.org
# desk-login-probe: test aid (kernel command line  loginprobe=1  makes desk-user-session run it in the background).  Writes PROBE lines
# about the identity and the permissions of THIS session to /tmp/loginprobe.log (desk-session shows that file on the console with
# deskdebug=1), which is how scripts/test-login.sh asserts "the desktop runs as that user".
L=/tmp/loginprobe.log
p() { echo "PROBE $*" >> $L; }
ck() { n=$1; shift; if "$@" 2>/dev/null; then p "PASS $n"; else p "FAIL $n"; fi; }
nck() { n=$1; shift; if "$@" 2>/dev/null; then p "FAIL $n (should not work)"; else p "PASS $n"; fi; }
if [ "$1" = late ]; then   # second look, started by the test through the Run dialog: Windows programs and what they printed
    for pid in $(pidof pe_load 2>/dev/null); do p "late proc pe_load pid $pid uid $(sed -n 's/^Uid:[ \t]*\([0-9]*\).*/\1/p' /proc/$pid/status)"; done
    for f in /tmp/probe-extra*.txt; do [ -f "$f" ] || continue; t=${f#/tmp/probe-extra-}; t=${t%.txt}; while IFS= read -r l; do p "EXTRA[$t] $l"; done < "$f"; done
    p "LATE DONE"; exit 0
fi
PD=$(sed -n "s/.*probedelay=\([0-9]*\).*/\1/p" /proc/cmdline); sleep ${PD:-12}
p "id: $(id)"
p "user=$(id -un) uid=$(id -u) home=$HOME runtime=$XDG_RUNTIME_DIR wayland=$WAYLAND_DISPLAY lang=$LANG"
for n in pomelo-compositor pomelo-login pomelo-panel pomelo-desktop pomelo-notify pomelo-input pomelo-greeter; do
    for pid in $(pidof $n 2>/dev/null); do p "proc $n pid $pid uid $(sed -n 's/^Uid:[ \t]*\([0-9]*\).*/\1/p' /proc/$pid/status)"; done
done
w=$(timeout 8 pomelo-loginctl who 2>&1); p "who: $w (rc=$?)"
[ "$(id -u)" != 0 ] && p "PASS not root" || p "FAIL still root"
nck "write /usr/bin" sh -c ': > /usr/bin/probe-x'
nck "write /etc" sh -c ': > /etc/probe-x'
nck "write /c/Windows" sh -c ': > /c/Windows/probe-x'
nck "write /c/Program Files" sh -c ': > "/c/Program Files/probe-x"'
nck "read /etc/shadow" sh -c 'cat /etc/shadow >/dev/null'
nck "setuid back to root" sh -c 'exec su -c true root'
ck "write HOME" sh -c ': > $HOME/probe-x && rm $HOME/probe-x'
ck "write HOME/Documents" sh -c ': > $HOME/Documents/probe-x && rm $HOME/Documents/probe-x'
[ -d /c/Users/$(id -un) ] && ck "write C:/Users/<me>" sh -c ': > /c/Users/$(id -un)/Documents/probe-x && rm /c/Users/$(id -un)/Documents/probe-x'
ck "write /tmp" sh -c ': > /tmp/probe-$(id -u) && rm /tmp/probe-$(id -u)'
ck "XDG_RUNTIME_DIR is mine" sh -c '[ -O "$XDG_RUNTIME_DIR" ]'
ck "wayland socket reachable" sh -c '[ -S "$XDG_RUNTIME_DIR/$WAYLAND_DISPLAY" ]'
for d in /home/*; do [ "$d" = "$HOME" ] && continue; [ -d "$d" ] && nck "other home $d" sh -c "ls $d >/dev/null"; done
p "DONE"
