#!/bin/bash
set -euo pipefail
if [[ "$(uname -s)" != Darwin ]]; then
  echo '此连接脚本用于MBP/macOS。'; exit 1
fi
if /usr/sbin/lsof -nP -iTCP:8765 -sTCP:LISTEN >/dev/null 2>&1; then
  echo '本机8765端口已被使用。请先确认并关闭原连接或服务，再运行；脚本不会停止其他进程。'
  exit 1
fi
printf '%s\n' '请保持NetBird已连接。正在通过私网SSH连接家里的36号。' \
 'SSH认证在本机终端完成；本脚本不保存密码，不转发SSH密钥。' \
 '连接后会打开本地工作台。任务提交成功后，可关闭此终端；36号继续执行。'
(
  for ((attempt=0; attempt<60; attempt++)); do
    if /usr/bin/curl --noproxy '*' --silent --fail --max-time 2 \
      http://127.0.0.1:8765/api/tasks | /usr/bin/grep -q 'client_connection_required'; then
      /usr/bin/open 'http://127.0.0.1:8765/'
      exit 0
    fi
    /bin/sleep 1
  done
  printf '%s\n' '尚未打开工作台，请检查NetBird和SSH连接。连接成功后手动打开http://127.0.0.1:8765/'
) &
portal_waiter=$!
cleanup() {
  # Bash may have reaped a finished waiter long before SSH disconnects.
  # Only signal a still-owned running job, never a possibly reused stale PID.
  if jobs -pr | /usr/bin/grep -qx "$portal_waiter"; then
    kill "$portal_waiter" 2>/dev/null || true
  fi
  wait "$portal_waiter" 2>/dev/null || true
}
trap cleanup EXIT
/usr/bin/ssh -N \
  -L 127.0.0.1:8765:127.0.0.1:8765 \
  -o ExitOnForwardFailure=yes -o ConnectTimeout=15 \
  -o ServerAliveInterval=30 -o ServerAliveCountMax=3 \
  -o ForwardAgent=no -o StrictHostKeyChecking=ask \
  moissestudio@100.82.213.196
