#!/usr/bin/env bash
# BlindVPN Native macOS .app Builder (Apple Silicon arm64 & Intel x86_64)
# Builds a zero-dependency ~1 MB native binary + /Applications/BlindVPN.app bundle.
set -euo pipefail

APP_DIR="/Applications/BlindVPN.app"
REPO_URL="https://github.com/blindlabs-ai/blindvpn.git"
BUILD_DIR="${TMPDIR:-/tmp}/blindvpn-macos-build"

if ! command -v cargo >/dev/null 2>&1; then
  echo "Installing Rust toolchain (rustup)..."
  curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y
  # shellcheck disable=SC1091
  source "$HOME/.cargo/env"
fi

rm -rf "$BUILD_DIR"
git clone --depth 1 "$REPO_URL" "$BUILD_DIR"
(cd "$BUILD_DIR" && cargo build --release --bin blindvpn)

mkdir -p "${APP_DIR}/Contents/MacOS" "${APP_DIR}/Contents/Resources"
cp -f "${BUILD_DIR}/target/release/blindvpn" "${APP_DIR}/Contents/MacOS/blindvpn-bin"
chmod 0755 "${APP_DIR}/Contents/MacOS/blindvpn-bin"

cat <<'LAUNCH' > "${APP_DIR}/Contents/MacOS/BlindVPN"
#!/usr/bin/env bash
exec "$(dirname "$0")/blindvpn-bin" desktop 127.0.0.1:10880
LAUNCH
chmod 0755 "${APP_DIR}/Contents/MacOS/BlindVPN"

cat <<'PLIST' > "${APP_DIR}/Contents/Info.plist"
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
  <key>CFBundleExecutable</key><string>BlindVPN</string>
  <key>CFBundleIdentifier</key><string>ai.blindlabs.blindvpn</string>
  <key>CFBundleName</key><string>BlindVPN</string>
  <key>CFBundlePackageType</key><string>APPL</string>
  <key>CFBundleShortVersionString</key><string>0.1.0</string>
  <key>LSMinimumSystemVersion</key><string>13.0</string>
  <key>NSHighResolutionCapable</key><true/>
</dict>
</plist>
PLIST

echo "Installed ${APP_DIR} ($(du -sh "${APP_DIR}" | awk '{print $1}'))."
echo "Launch with: open -a BlindVPN"
