#!/bin/bash
set -e
# Runs inside headless-desktop; all state goes into RUN_DIR.
mkdir -p "$RUN_DIR"
ffmpeg -hide_banner -loglevel error -y -f x11grab -video_size 1920x1080 -framerate 15 -i "$DISPLAY" -c:v libx264 -preset ultrafast -crf 23 -pix_fmt yuv420p "$RUN_DIR/raw.mp4" > "$RUN_DIR/ffmpeg.log" 2>&1 &
recorder=$!
echo "$recorder" > "$RUN_DIR/recorder.pid"
"$CHECKOUT/apps/desktop/node_modules/electron/dist/electron" "$DRIVER" --no-sandbox --disable-gpu > "$RUN_DIR/app.log" 2>&1 &
electron_pid=$!
echo "$electron_pid" > "$RUN_DIR/electron.pid"
for n in $(seq 1 900); do
 if [ -f "$RUN_DIR/install-start" ]; then break; fi
 if ! kill -0 "$electron_pid" 2>/dev/null; then break; fi
 sleep 0.1
done
if [ -f "$RUN_DIR/install-start" ]; then
 sleep 2
 window_id=$(xdotool search --onlyvisible --pid "$electron_pid" | head -1)
 if [ -n "$window_id" ]; then
  xdotool windowfocus "$window_id"
  xdotool key --window "$window_id" ctrl+comma
 fi
 sleep 2
 import -window root "$RUN_DIR/during-install.png"
fi
wait "$electron_pid" || true
# app.relaunch starts the same real app after its original process exits.
for n in $(seq 1 200); do
 if [ -f "$RUN_DIR/relaunched" ]; then
  sleep 1
  import -window root "$RUN_DIR/stable-a.png"
  sleep 0.5
  import -window root "$RUN_DIR/stable-b.png"
  if cmp -s "$RUN_DIR/stable-a.png" "$RUN_DIR/stable-b.png"; then
   cp "$RUN_DIR/stable-b.png" "$RUN_DIR/relaunch-summary.png"
  fi
  sleep 1
  break
 fi
 sleep 0.1
done
kill -INT "$recorder"
wait "$recorder" || true
