#!/usr/bin/env bash
set -euo pipefail
# Run from a current-main checkout with vp i already completed.
# Supply the downloaded scenario as scripts/scenarios/gitlab-offline-remote.e2e.ts.
run_dir=$(mktemp -d)
export GLAB_CONFIG_DIR="$run_dir/glab"
export T3CODE_DEV_SEED=0
mkdir -p "$GLAB_CONFIG_DIR"
cat > "$GLAB_CONFIG_DIR/config.yml" <<'YAML'
check_update: false
hosts:
  localhost:19443:
    api_host: localhost:19443
    token: synthetic-offline-fixture
YAML
# e2e starts apps with an allowlisted environment. Keep the isolated config.
python3 - <<'PY'
p='scripts/e2e.config.ts'
s=open(p).read()
if 'inheritEnv: ["GLAB_CONFIG_DIR", "T3CODE_DEV_SEED"]' not in s:
    s=s.replace('executable: resolved.node,', 'executable: resolved.node,\n          inheritEnv: ["GLAB_CONFIG_DIR", "T3CODE_DEV_SEED"],')
    open(p,'w').write(s)
PY
python3 -u - <<'PY' > "$run_dir/offline-host.log" 2>&1 &
import socket, threading
server = socket.socket()
server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server.bind(('127.0.0.1', 19443))
server.listen()
def hold(connection):
    try:
        while connection.recv(65536): pass
    finally: connection.close()
while True:
    connection, _ = server.accept()
    threading.Thread(target=hold, args=(connection,), daemon=True).start()
PY
host_pid=$!
trap 'kill "$host_pid"' EXIT
# localhost resolves, but the fixture never answers the TLS handshake: an offline host.
glab config get api_host --host localhost:19443
vp run scenarios:prove scripts/scenarios/gitlab-offline-remote.e2e.ts \
  --base "$(git merge-base origin/main 563a2fcd2799b84bdfa079de7927f37362593ee1)" \
  --head 563a2fcd2799b84bdfa079de7927f37362593ee1 \
  --upload-command 'ghdrop upload'
