#!/bin/bash
#
# build_strongswan.sh — build strongSwan from src/strongswan-<ver>.tar.gz as a
# MONOLITHIC macOS build, so all plugins are compiled into libstrongswan/libcharon
# instead of being dlopen'd from a compile-time directory. That is what makes the
# result relocatable: a bundled charon needs no external plugin directory.
#
# Crypto comes from the openssl plugin (AES, SHA, MODP DH, RSA, X.509), so the
# only external runtime dependency is libcrypto, which stage_strongswan.sh bundles
# and relocates alongside the strongSwan libraries.
#
# Output: src/strongswan-install/ (gitignored) containing bin/swanctl,
# libexec/ipsec/charon, lib/libstrongswan.dylib, lib/libcharon.dylib,
# lib/libvici.dylib, etc. — consumed by stage_strongswan.sh.
#
# Usage: Scripts/build_strongswan.sh [version]

set -euo pipefail

VERSION="${1:-6.0.7}"
ROOT="$(cd "$(dirname "$0")/.." && pwd)"
SRC="$ROOT/src"
TARBALL="$SRC/strongswan-$VERSION.tar.gz"
BUILD="$SRC/strongswan-$VERSION"
INSTALL="$SRC/strongswan-install"

# Our own OpenSSL, built for the same deployment target (Scripts/build_openssl.sh).
OPENSSL_PREFIX="$SRC/openssl-install"

[ -f "$TARBALL" ] || { echo "error: $TARBALL not found"; exit 1; }
[ -d "$OPENSSL_PREFIX/lib" ] || { echo "error: $OPENSSL_PREFIX not found — run Scripts/build_openssl.sh first"; exit 1; }

echo "==> Extracting $TARBALL"
[ -d "$BUILD" ] || tar -C "$SRC" -xzf "$TARBALL"

# Match the app's deployment target so the bundled dylibs aren't flagged as
# "built for newer version" when linked into a macOS 14 binary (and so they don't
# use APIs unavailable on 14 at runtime).
DEPLOY_TARGET=14.0
export MACOSX_DEPLOYMENT_TARGET="$DEPLOY_TARGET"

echo "==> Configuring (monolithic, openssl, macOS kernel plugins, deploy $DEPLOY_TARGET)"
cd "$BUILD"
rm -rf "$INSTALL"
# A fresh tree configures cleanly; only re-run if not yet configured.
make distclean >/dev/null 2>&1 || true
./configure \
  --prefix="$INSTALL" \
  --enable-monolithic \
  --disable-kernel-netlink \
  --enable-kernel-pfkey \
  --enable-kernel-pfroute \
  --enable-osx-attr \
  --enable-unity \
  --enable-eap-identity \
  --enable-eap-md5 \
  --enable-eap-mschapv2 \
  --enable-eap-gtc \
  --enable-eap-tls \
  --disable-scripts \
  CFLAGS="-mmacosx-version-min=$DEPLOY_TARGET" \
  CPPFLAGS="-I$OPENSSL_PREFIX/include" \
  LDFLAGS="-mmacosx-version-min=$DEPLOY_TARGET -L$OPENSSL_PREFIX/lib" \
  PKG_CONFIG_PATH="$OPENSSL_PREFIX/lib/pkgconfig"

echo "==> Building (this takes a few minutes)"
make -j"$(sysctl -n hw.ncpu)"

echo "==> Installing into $INSTALL"
make install

echo "==> Done. Key products:"
ls -la "$INSTALL/lib/"libstrongswan*.dylib "$INSTALL/lib/"libcharon*.dylib \
       "$INSTALL/lib/"libvici*.dylib "$INSTALL/libexec/ipsec/charon" \
       "$INSTALL/bin/swanctl" "$INSTALL/sbin/charon" 2>/dev/null || true
