#!/usr/bin/env bash
# Launch matrix_client_pc.exe on Windows with E2E mode enabled.
# Fire-and-forget — does NOT block waiting for confirmation.
# Use ./scripts/check_e2e.sh afterwards to verify endpoints.
set -euo pipefail

APP_DIR_WIN='C:\Users\lucas\Desktop\apps\matrix_client_pc'

echo "[e2e] killing existing matrix_client_pc.exe"
taskkill.exe /IM matrix_client_pc.exe /F 2>/dev/null || true

LAST_USER="/mnt/c/Users/lucas/AppData/Roaming/matrix_client_pc/last_user.txt"
if [ -f "$LAST_USER" ]; then
  echo "[e2e] wiping last_user.txt"
  rm -f "$LAST_USER"
fi

ADMIN_TOKEN=$(pass matrix/synapse-admin-token 2>/dev/null | head -n1 || true)
if [ -z "$ADMIN_TOKEN" ]; then
  echo "[e2e] WARN: pass matrix/synapse-admin-token failed — /signin_admin will require body admin_token"
fi

echo "[e2e] launching via powershell with MATRIX_CLIENT_PC_E2E=1 + BIND_ALL=1 + admin token"
# MATRIX_CLIENT_PC_E2E_BIND_ALL=1 → E2E HTTP server binds 0.0.0.0 so WSL can
# curl it directly (Vite shim + tests). Without it, server only listens on
# 127.0.0.1 (production / single-machine testing).
# MATRIX_SYNAPSE_ADMIN_TOKEN → /signin_admin uses it as the default access
# token (resolves user_id + device_id via whoami).
powershell.exe -NoProfile -Command "\$env:MATRIX_CLIENT_PC_E2E='1'; \$env:MATRIX_CLIENT_PC_E2E_BIND_ALL='1'; \$env:MATRIX_SYNAPSE_ADMIN_TOKEN='$ADMIN_TOKEN'; Start-Process -FilePath '$APP_DIR_WIN\\matrix_client_pc.exe' -WorkingDirectory '$APP_DIR_WIN'" >/dev/null 2>&1 &
disown
echo "[e2e] fired. Use scripts/check_e2e.sh to verify endpoints."
