#!/usr/bin/env bash
# build-libbox.sh — 把 sing-box 编成嵌入式核心库(方案B / docs/vpn-core-embedding.md)
#
# 产物:
#   apple  → Libbox.xcframework  (macOS System Extension / iOS Packet Tunnel 链接)
#   android→ Libbox.aar          (VpnService 集成)
#
# 关键:用 sagernet 的 gomobile **fork**(非上游 golang.org/x/mobile)。
# sing-box 版本必须与节点对齐(当前节点 1.13.13)。
#
# 用法:
#   bash scripts/build-libbox.sh apple macos     # 只编 macOS(快)
#   bash scripts/build-libbox.sh apple           # 全 Apple(ios+sim+tvos+macos,慢)
#   bash scripts/build-libbox.sh android
#   SINGBOX_VERSION=v1.13.13 WORK=/tmp/x bash scripts/build-libbox.sh apple macos
set -euo pipefail

SINGBOX_VERSION="${SINGBOX_VERSION:-v1.13.13}"   # 与节点 sing-box 对齐
TARGET="${1:-apple}"                              # apple | android
PLATFORM="${2:-}"                                 # macos | ios | "" (全 Apple)
WORK="${WORK:-/tmp/pangolin-libbox}"

command -v go >/dev/null || { echo "✗ 需要 Go"; exit 1; }

echo "==> [1/3] 安装 sagernet/gomobile fork v0.1.12(非上游)"
go install github.com/sagernet/gomobile/cmd/gomobile@v0.1.12
go install github.com/sagernet/gomobile/cmd/gobind@v0.1.12
export PATH="$PATH:$(go env GOPATH)/bin"
gomobile init

echo "==> [2/3] 拉 sing-box $SINGBOX_VERSION 源码"
mkdir -p "$WORK"
rm -rf "$WORK/sing-box"
git clone --depth 1 --branch "$SINGBOX_VERSION" https://github.com/SagerNet/sing-box.git "$WORK/sing-box"
cd "$WORK/sing-box"

echo "==> [3/3] 用官方 build_libbox 编核心库"
if [ "$TARGET" = "apple" ]; then
  if [ -n "$PLATFORM" ]; then
    go run ./cmd/internal/build_libbox -target apple -platform "$PLATFORM"
  else
    go run ./cmd/internal/build_libbox -target apple
  fi
  echo "✅ 产物: $WORK/sing-box/Libbox.xcframework"
  echo "   下一步(P1):拖进 macOS System Extension target 链接;Headers 暴露"
  echo "   LibboxNewService / LibboxCommandClient(状态·速率)等 API。"
else
  go run ./cmd/internal/build_libbox -target android
  echo "✅ 产物: $WORK/sing-box/Libbox.aar"
fi
