#!/bin/bash
# Started by Plasma's autostart inside the headless session. Keeps krfb
# running (re-reading the password each time it starts).
STATE="$XDG_RUNTIME_DIR/linuxdoors-plasma68-vnc"
[ -n "$LINUXDOORS_PLASMA68_W" ] || exit 0   # only in the headless VNC session
# `ss` (iproute2) is in /usr/sbin, which a normal user's session PATH lacks
export PATH="$PATH:/usr/sbin:/sbin"
# Pre-authorize remote control for this private session's portal: the empty
# app id covers host (non-sandboxed) apps, org.kde.krfb covers krfb if it
# registers its id. Stored under this session's own XDG_DATA_HOME.
for app in "" org.kde.krfb; do
  gdbus call --session --dest org.freedesktop.impl.portal.PermissionStore \
    --object-path /org/freedesktop/impl/portal/PermissionStore \
    --method org.freedesktop.impl.portal.PermissionStore.SetPermission \
    kde-authorized true remote-desktop "$app" "['yes']" >/dev/null || true
done
while :; do
  PASS="$(cat "$STATE/password" 2>/dev/null)"
  OBS="$(python3 -c 'import sys; print("".join(c if ord(c) <= 0x21 else chr(0x1001F - ord(c)) for c in sys.argv[1]))' "$PASS")"
  kwriteconfig6 --file krfbrc --group TCP --key useDefaultPort false
  kwriteconfig6 --file krfbrc --group TCP --key port 5901
  kwriteconfig6 --file krfbrc --group TCP --key publishService false
  kwriteconfig6 --file krfbrc --group Security --key noWallet true
  kwriteconfig6 --file krfbrc --group Security --key allowDesktopControl true
  kwriteconfig6 --file krfbrc --group Security --key allowUnattendedAccess true
  kwriteconfig6 --file krfbrc --group Security --key unattendedPassword "$OBS"
  kwriteconfig6 --file krfbrc --group FrameBuffer --key preferredFrameBufferPlugin pw
  kwriteconfig6 --file krfbrc --group MainWindow --key startMinimized true
  /opt/plasma68/bin/krfb --nodialog &
  KPID=$!
  # keep checking for as long as krfb runs (a fixed 60 s window missed a
  # slow first start and left the session marked "not up" forever)
  while kill -0 "$KPID" 2>/dev/null; do
    if ss -ltn 2>/dev/null | grep -q '127.0.0.1:5901 '; then touch "$STATE/krfb-ready"; break; fi
    sleep 1
  done
  wait "$KPID"
  rm -f "$STATE/krfb-ready"
  sleep 1
done
