#!/bin/bash
set -eu
side=$1
out="$MAC_WORK/capture-$side-$(date +%s)"
printf "%s\n" "$out" > "$MAC_WORK/latest-$side"
mkdir -p "$out"
key() { osascript -e "tell application \"System Events\" to tell process \"Safari\" to $1" >/dev/null; }
key 'key code 53'
ffmpeg -y -f avfoundation -framerate 10 -i '0:none' -t 30 -c:v libx264 -pix_fmt yuv420p "$out/raw.mov" > "$out/record.log" 2>&1 &
rec=$!
sleep 7
key 'keystroke "k" using command down'
sleep 1
key 'keystroke "new project"'
sleep 1
key 'key code 36'
sleep 1
key 'keystroke "safari-repro"'
sleep 2
key 'key code 36'
sleep 2
key 'key code 36 using command down'
sleep 2
osascript <<'APPLESCRIPT'
tell application "System Events" to tell process "Safari"
  set matches to entire contents of front window
  repeat with el in matches
    try
      if role of el is "AXButton" and name of el is "Create (Enter)" then
        click el
        delay 1
        click el
        exit repeat
      end if
    end try
  end repeat
end tell
APPLESCRIPT
sleep 3
sleep 1
screencapture -x "$out/final-1.png"
sleep 0.5
screencapture -x "$out/final-2.png"
wait "$rec"
