#!/bin/zsh
# zyginit start hook for the Hammerhead xdm graphical login.
#
# DECOUPLED server model: xdm-managed X-server startup hangs on illumos VT
# acquisition ("using VT number 2" never completes) — while a separately
# started server works fine. So we start our own Xorg here (the proven M2/M3
# launch), then run xdm against it as a FOREIGN display (xdm draws only the
# greeter + runs the session; it does not start/stop the server). See
# docs/roadmap/DESKTOP_XLIBRE_XDM_GREETER_PLAN.md.
#
# MIT-MAGIC-COOKIE-1 access control so the display is authorized (no
# "unsecure session" warning). Absolute paths only (zyginit convention).
set -u

XAUTHDIR=/var/lib/xdm/authdir/authfiles
XAUTH="$XAUTHDIR/A:0"

# Robustness: a crashed prior instance (or a zyginit restart whose
# backgrounded Xorg orphaned past the contract teardown) can leave a stale
# server, X lock, or xdm pid file. Clear them first so a restart does NOT
# accumulate X servers. We are still zsh here (xdm is exec'd at the end), so
# pkill xdm cannot hit this script.
/usr/bin/pkill -9 -x Xorg 2>/dev/null
/usr/bin/pkill -9 -x xdm 2>/dev/null
/bin/sleep 1

/bin/mkdir -p "$XAUTHDIR"
/bin/rm -f "$XAUTH" /var/run/xdm.pid /tmp/.X0-lock /tmp/.X11-unix/X0 2>/dev/null

# Fresh cookie, shared between the server (-auth) and every X client via
# XAUTHORITY (xdm greeter, Xsetup, and the user session all inherit it).
COOKIE=$(/usr/bin/openssl rand -hex 16)
/usr/local/bin/xauth -f "$XAUTH" add :0 . "$COOKIE"
export XAUTHORITY="$XAUTH"

# Start Xorg with auth, in the background (the launch that works on our console).
/usr/local/bin/Xorg :0 -nolisten tcp -auth "$XAUTH" -config /etc/X11/xorg.conf &

# Wait for the server socket (illumos has no seq/timeout(1)).
i=0
while [ ! -S /tmp/.X11-unix/X0 ] && [ "$i" -lt 60 ]; do /bin/sleep 0.25; i=$((i + 1)); done
/bin/sleep 1

# Run xdm on the foreign, authorized server. exec so zyginit supervises xdm;
# Xorg is in the same process contract and is torn down with the service.
exec /usr/local/bin/xdm -nodaemon -config /usr/local/lib/X11/xdm/xdm-config
