#!/bin/bash
# 每個 Bot 一個螢幕 (Grok Bot's split: one computer per account, a screen of its own per bot, so
# bots use the desktop and the browser side by side instead of waiting for each other on :1).
# The box's own screen :1 stays as it is (the person's shared desktop).
#
#   anybot-screen up <key>     the screen of <key> (a bot), made when it isn't there; prints
#                              KEY=VALUE lines: DISPLAY, DBUS_SESSION_BUS_ADDRESS, VNC_PORT, CDP_PORT,
#                              PROFILE. Using it marks it used (see reap).
#   anybot-screen down <key>   close it (its browser too); the browser profile stays on disk
#   anybot-screen list         one line per open screen: key display seconds-since-used
#   anybot-screen reap <secs>  close the screens nobody used for that long
#
# Exit 3 when ANYBOT_MAX_SCREENS screens are open already: the keys holding them are printed.
# (What it starts in the background never keeps the lock: each gets 8>&-.)
# Runs as the bot user (how AnyBot calls it) or as root (the desktop is the bot user's either way).
# Each open screen is in /tmp/anybot-vnc-tokens, so the box's one web viewer (port 6080) shows any
# of them: ?path=websockify%3Ftoken%3D<key> ("main" is the shared screen).
# <key>-t<n> is a temporary screen (a 支線's, beside its main bot <key>): its browser starts as a
# copy of <key>'s (box/browser), and that copy is removed with the screen.
set -u
DIR=/tmp/anybot-screens
MAX=${ANYBOT_MAX_SCREENS:-6}
# Displays :10, :11, … — VNC on 5900+n and the browser's DevTools on 9300+n, both on 127.0.0.1.
FIRST=10
mkdir -p "$DIR" 2>/dev/null; chmod 1777 "$DIR" 2>/dev/null

TOKENS=/tmp/anybot-vnc-tokens

key_ok() { [[ "$1" =~ ^[A-Za-z0-9_-]{1,48}$ ]]; }
# The bot user's side of the desktop (XFCE, the buses): as is when we are the bot user.
as_bot() { if [ "$(id -u)" = 0 ]; then su bot -c "$1"; else sh -c "$1"; fi; }
token_set() { { grep -v "^$1: " "$TOKENS" 2>/dev/null; [ -n "${2:-}" ] && echo "$1: localhost:$2"; } > "$TOKENS.new"; mv -f "$TOKENS.new" "$TOKENS"; }
alive() { [ -n "${1:-}" ] && kill -0 "$1" 2>/dev/null; }

# The screen's processes (Xtigervnc, its dbus, the accessibility bus, the desktop, the browser),
# killed youngest first.
close() {
  local d=$DIR/$1
  [ -d "$d" ] || return 0
  local disp; disp=$(cat "$d/display" 2>/dev/null)
  if [ -n "$disp" ]; then
    # (The browser gets a moment to write its profile before it is killed.)
    local prof="--user-data-dir=/home/bot/.config/anybot-profiles/$1( |\$)"
    if pkill -u bot -f -- "$prof" 2>/dev/null; then
      for _ in $(seq 1 20); do pgrep -u bot -f -- "$prof" >/dev/null || break; sleep 0.1; done
      pkill -9 -u bot -f -- "$prof" 2>/dev/null
    fi
    for p in $(cat "$d/pids" 2>/dev/null | tac); do kill "$p" 2>/dev/null; done
    sleep 0.3
    for p in $(cat "$d/pids" 2>/dev/null); do kill -9 "$p" 2>/dev/null; done
    rm -f "/tmp/.X$disp-lock" "/tmp/.X11-unix/X$disp"
  fi
  token_set "$1"
  rm -rf "$d"
  [[ "$1" =~ -t[0-9]+$ ]] && rm -rf "/home/bot/.config/anybot-profiles/$1"
  return 0
}

print_env() {
  local d=$DIR/$1
  touch "$d/last"
  cat "$d/env"
}

up() {
  local key=$1 d=$DIR/$1
  # Already there and its X server alive: just say where.
  if [ -f "$d/env" ] && alive "$(head -1 "$d/pids" 2>/dev/null)"; then
    print_env "$key"
    return 0
  fi
  close "$key"
  local open=() n disp=""
  for s in "$DIR"/*/; do [ -f "$s/env" ] && open+=("$(basename "$s")"); done
  if [ "${#open[@]}" -ge "$MAX" ]; then
    printf 'FULL=%s\n' "${open[*]}"
    exit 3
  fi
  for ((n = FIRST; n < FIRST + 64; n++)); do
    [ -e "/tmp/.X$n-lock" ] || [ -e "/tmp/.X11-unix/X$n" ] || grep -qx "$n" "$DIR"/*/display 2>/dev/null || { disp=$n; break; }
  done
  [ -n "$disp" ] || { echo "ERROR=no free display" ; exit 1; }
  mkdir -p "$d"
  echo "$disp" > "$d/display"
  local geom="${SCREEN_SIZE:-1440x900x24}"; geom="${geom%x*}"
  local sec="-SecurityTypes None"
  [ -r /home/bot/.vnc/passwd ] && sec="-SecurityTypes VncAuth -rfbauth /home/bot/.vnc/passwd"
  # shellcheck disable=SC2086
  Xtigervnc ":$disp" -geometry "$geom" -depth 24 -rfbport $((5900 + disp)) -localhost $sec -AlwaysShared -AcceptCutText -SendCutText \
    -UseBlacklist 0 -IdleTimeout 0 -MaxIdleTime 0 -MaxDisconnectionTime 0 -MaxConnectionTime 0 -s 0 -dpms -desktop "Bot 的電腦 · $key" -ac -noreset \
    >"$d/xvnc.log" 2>&1 8>&- &
  echo $! > "$d/pids"
  for _ in $(seq 1 50); do xdpyinfo -display ":$disp" >/dev/null 2>&1 && break; sleep 0.1; done
  xdpyinfo -display ":$disp" >/dev/null 2>&1 || { echo "ERROR=the screen did not start"; close "$key"; exit 1; }
  # A session bus and an accessibility registry of its own: the controls listed for this screen
  # are this screen's apps only.
  local out bus buspid
  out=$(as_bot 'cd /home/bot && dbus-launch --sh-syntax' 8>&-)
  bus=$(printf '%s\n' "$out" | sed -n "s/^DBUS_SESSION_BUS_ADDRESS='\(.*\)';\$/\1/p")
  buspid=$(printf '%s\n' "$out" | sed -n 's/^DBUS_SESSION_BUS_PID=\([0-9]*\);$/\1/p')
  [ -n "$buspid" ] && echo "$buspid" >> "$d/pids"
  for c in /usr/libexec/at-spi-bus-launcher /usr/lib/at-spi2-core/at-spi-bus-launcher; do
    [ -x "$c" ] && { as_bot "DISPLAY=:$disp DBUS_SESSION_BUS_ADDRESS=$bus setsid $c --launch-immediately >/dev/null 2>&1 & echo \$!" 8>&- >> "$d/pids"; break; }
  done
  for c in /usr/libexec/at-spi2-registryd /usr/lib/at-spi2-core/at-spi2-registryd; do
    [ -x "$c" ] && { as_bot "DISPLAY=:$disp DBUS_SESSION_BUS_ADDRESS=$bus setsid $c >/dev/null 2>&1 & echo \$!" 8>&- >> "$d/pids"; break; }
  done
  as_bot "DISPLAY=:$disp xrdb -nocpp -merge /home/bot/.Xresources" 2>/dev/null
  xsetroot -display ":$disp" -solid '#2f343f'
  # The same desktop as the shared screen (start.sh): window manager, wallpaper, panel. Their
  # settings are the shared screen's files, read by this bus's own xfconfd. (A simple command each,
  # so $! is the program itself and close() can stop it; the panel's is the loop that brings it
  # back when it is closed, as on the shared screen, and ends with the screen.)
  local x="DISPLAY=:$disp DBUS_SESSION_BUS_ADDRESS=$bus setsid"
  as_bot "$x xfwm4 --compositor=off --sm-client-disable >/dev/null 2>&1 & echo \$!" 8>&- >> "$d/pids"
  sleep 0.3
  as_bot "$x xfdesktop --disable-wm-check --sm-client-disable >/dev/null 2>&1 & echo \$!" 8>&- >> "$d/pids"
  as_bot "$x sh -c 'while xdpyinfo >/dev/null 2>&1; do xfce4-panel --disable-wm-check --sm-client-disable; sleep 1; done' >/dev/null 2>&1 & echo \$!" 8>&- >> "$d/pids"
  # Copy and paste with the person's computer (as on the shared screen: start.sh).
  as_bot "DISPLAY=:$disp setsid vncconfig -nowin >/dev/null 2>&1 & echo \$!" 8>&- >> "$d/pids"
  {
    echo "DISPLAY=:$disp"
    echo "DBUS_SESSION_BUS_ADDRESS=$bus"
    echo "VNC_PORT=$((5900 + disp))"
    echo "CDP_PORT=$((9300 + disp))"
    echo "PROFILE=/home/bot/.config/anybot-profiles/$key"
  } > "$d/env"
  chmod 644 "$d/env" "$d/display"
  token_set "$key" $((5900 + disp))
  print_env "$key"
}

reap() {
  local limit=$1 now; now=$(date +%s)
  for s in "$DIR"/*/; do
    [ -d "$s" ] || continue
    local k; k=$(basename "$s")
    local last; last=$(stat -c %Y "$s/last" 2>/dev/null || echo 0)
    if [ $((now - last)) -ge "$limit" ] || ! alive "$(head -1 "$s/pids" 2>/dev/null)"; then close "$k"; echo "closed $k"; fi
  done
}

cmd=${1:-}; arg=${2:-}
exec 8>"$DIR/.lock"
flock -w 20 8 || { echo "ERROR=busy"; exit 1; }
case "$cmd" in
  up) key_ok "$arg" || { echo "ERROR=bad key"; exit 2; }; up "$arg" ;;
  down) key_ok "$arg" || { echo "ERROR=bad key"; exit 2; }; close "$arg" ;;
  list)
    now=$(date +%s)
    for s in "$DIR"/*/; do
      [ -f "$s/env" ] || continue
      echo "$(basename "$s") :$(cat "$s/display") $((now - $(stat -c %Y "$s/last" 2>/dev/null || echo "$now")))"
    done ;;
  reap) [[ "$arg" =~ ^[0-9]+$ ]] || { echo "ERROR=seconds"; exit 2; }; reap "$arg" ;;
  *) sed -n '2,15p' "$0"; exit 2 ;;
esac
