#!/bin/bash
# Resolve sibling OnceSend-Mac next to this .app
APP_BUNDLE="$(cd "$(dirname "$0")/../.." && pwd)"
PARENT="$(cd "$APP_BUNDLE/.." && pwd)"
DIR="$PARENT/OnceSend-Mac"

if [ ! -x "$DIR/runtime/bin/node" ]; then
  osascript -e 'display dialog "找不到 OnceSend-Mac 文件夹。请把 OnceSend.app 和 OnceSend-Mac 放在同一目录（例如 Documents/oncetalk）。" buttons {"好"} default button 1 with icon stop'
  exit 1
fi

NODE="$DIR/runtime/bin/node"
APPJS="$DIR/app/server.js"
PORT=8787
export ONCESEND_HTTPS=1
export ONCESEND_CERT_DIR="${HOME}/Library/Application Support/OnceSend/certs"
mkdir -p "$HOME/Library/Logs" "$HOME/Library/Application Support" "$ONCESEND_CERT_DIR"
LOG="$HOME/Library/Logs/OnceSend.log"
OPEN_URL="https://127.0.0.1:$PORT"

if lsof -iTCP:"$PORT" -sTCP:LISTEN >/dev/null 2>&1; then
  open "$OPEN_URL" 2>/dev/null || open "http://127.0.0.1:$PORT"
  HINT=$(curl -skf "$OPEN_URL/api/lan-hint" 2>/dev/null || curl -sf "http://127.0.0.1:$PORT/api/lan-hint" 2>/dev/null || echo '{}')
  PHONE=$(/usr/bin/python3 -c "import json,sys; d=json.load(sys.stdin); ips=d.get('ips') or []; port=d.get('port') or 8787; scheme='https' if d.get('https') else 'http'; print(('%s://%s:%s'%(scheme,ips[0],port)) if ips else '（未检测到局域网IP，请看页面）')" <<<"$HINT" 2>/dev/null || echo "见页面提示")
  osascript -e "display dialog \"OnceSend 已在运行。\n本机页面已打开（若提示证书：高级→继续访问）。\n手机请打开：\n$PHONE\n\n文字和文件走设备直连，电脑不是中转站。\" buttons {\"知道了\"} default button 1 with title \"OnceSend\""
  exit 0
fi

nohup env ONCESEND_HTTPS=1 ONCESEND_CERT_DIR="$ONCESEND_CERT_DIR" "$NODE" "$APPJS" >>"$LOG" 2>&1 &
PID=$!
echo "$PID" > "$HOME/Library/Application Support/OnceSend.pid"

for i in $(seq 1 40); do
  if curl -skf "$OPEN_URL/api/lan-hint" >/dev/null 2>&1; then
    break
  fi
  if curl -sf "http://127.0.0.1:$PORT/api/lan-hint" >/dev/null 2>&1; then
    OPEN_URL="http://127.0.0.1:$PORT"
    break
  fi
  if ! kill -0 "$PID" 2>/dev/null; then
    osascript -e 'display dialog "OnceSend 启动失败，请查看 ~/Library/Logs/OnceSend.log，或改用 OnceSend-Mac 里的「启动 OnceSend.command」。" buttons {"好"} default button 1 with icon stop'
    exit 1
  fi
  sleep 0.25
done

HINT=$(curl -skf "https://127.0.0.1:$PORT/api/lan-hint" 2>/dev/null || curl -sf "http://127.0.0.1:$PORT/api/lan-hint" 2>/dev/null || echo '{}')
open "$OPEN_URL" 2>/dev/null || true
PHONE=$(/usr/bin/python3 -c "import json,sys; d=json.load(sys.stdin); ips=d.get('ips') or []; port=d.get('port') or 8787; scheme='https' if d.get('https') else 'http'; print(('%s://%s:%s'%(scheme,ips[0],port)) if ips else '（未检测到局域网IP，请看页面）')" <<<"$HINT" 2>/dev/null || echo "见页面提示")

osascript <<OSA
display dialog "OnceSend v0.3 已启动（设备直连）。

本机页面已打开。若提示证书不受信任：高级 → 继续访问。
手机请连同一 Wi‑Fi，浏览器打开：
$PHONE

文字和文件在设备之间直传，不经电脑中转。
停止：双击 OnceSend-Mac 里的「停止 OnceSend.command」" buttons {"知道了"} default button 1 with title "OnceSend"
OSA
