#!/bin/bash
# Usage: linuxdoors-budgie-vnc [WxH] [vnc-password]
#        linuxdoors-budgie-vnc --stop
# Starts (or reuses) a headless Budgie session for the calling user and serves
# it with wayvnc on 127.0.0.1:5902 (VNC username "x2go"). Run as the target
# user inside a real user session (XDG_RUNTIME_DIR set), e.g. over x2go's SSH
# connection. No password argument = keep the current one.
set -e
UNIT=budgie-vnc
if [ "$1" = "--stop" ]; then
  if systemctl --user is-active --quiet "$UNIT.service" 2>/dev/null; then
    systemctl --user stop "$UNIT.service" 2>&1 || echo "FAILED_TO_STOP: $UNIT.service"
  fi
  exit 0
fi
GEOM="${1:-1920x1080}"
PASS="${2:-}"
case "$GEOM" in
  [0-9]*x[0-9]*) case "$GEOM" in *[!0-9x]*) echo "linuxdoors-budgie-vnc: bad size $GEOM" >&2; exit 2;; esac ;;
  *) echo "linuxdoors-budgie-vnc: bad size $GEOM (want WxH)" >&2; exit 2 ;;
esac
if [ -z "$XDG_RUNTIME_DIR" ]; then
  echo "linuxdoors-budgie-vnc: run this inside a real user session (XDG_RUNTIME_DIR must be set)" >&2
  exit 1
fi
STATE="$XDG_RUNTIME_DIR/linuxdoors-budgie-vnc"
mkdir -p "$STATE"; chmod 700 "$STATE"
OLDPASS="$(cat "$STATE/password" 2>/dev/null || true)"
if [ -n "$PASS" ]; then (umask 077; printf '%s' "$PASS" > "$STATE/password"); fi
if [ ! -s "$STATE/password" ]; then
  echo "linuxdoors-budgie-vnc: no VNC password given and none set yet" >&2
  exit 1
fi
case "$(cat "$STATE/password")" in *[[:space:]]*|*=*) echo "linuxdoors-budgie-vnc: password must not contain spaces or '='" >&2; exit 2;; esac

RUNNING=""
if systemctl --user is-active --quiet "$UNIT.service" 2>/dev/null; then
  RUNNING="$(cat "$STATE/geometry" 2>/dev/null || true)"
fi
if [ -z "$RUNNING" ]; then
  systemctl --user stop "$UNIT.service" >/dev/null 2>&1 || true
  systemctl --user reset-failed "$UNIT.service" >/dev/null 2>&1 || true
  echo "$GEOM" > "$STATE/geometry"
  rm -f "$STATE/ready"
  systemd-run --user --unit="$UNIT" --collect --property=KillMode=control-group \
    /usr/libexec/linuxdoors-budgie-vnc-session "$GEOM" >/dev/null
elif [ "$RUNNING" != "$GEOM" ] || { [ -n "$PASS" ] && [ "$PASS" != "$OLDPASS" ]; }; then
  # same session: the in-session loop resizes the output and restarts
  # wayvnc with the new password
  echo "$GEOM" > "$STATE/geometry"
  rm -f "$STATE/ready"
  pkill -u "$(id -u)" -x wayvnc >/dev/null 2>&1 || true
fi
for i in $(seq 1 120); do
  [ -e "$STATE/ready" ] && break
  systemctl --user is-active --quiet "$UNIT.service" || break
  sleep 1
done
if [ -e "$STATE/ready" ]; then
  echo "Budgie is running headless and reachable over VNC on 127.0.0.1:5902."
else
  echo "linuxdoors-budgie-vnc: the session did not come up; see: journalctl --user -u $UNIT" >&2
  journalctl --user -u "$UNIT" -n 25 --no-pager >&2 2>/dev/null || true
  exit 1
fi
