#!/bin/bash
#
# build_openssl.sh — build OpenSSL from src/openssl-<ver>.tar.gz for macOS 14.0 as
# a STATIC, position-independent libcrypto.a. strongSwan links it into
# libstrongswan (the openssl plugin), so there is no bundled libcrypto dylib at
# all — and it targets the same deployment as the rest of SwanDesk (a Homebrew
# bottle is built for the current macOS, e.g. 26.0, which would be unsafe on 14).
# Removes the only remaining Homebrew dependency in the crypto path.
#
# Output: src/openssl-install/ (gitignored) with lib/libcrypto.a, include/,
# lib/pkgconfig — consumed by build_strongswan.sh.
#
# Usage: Scripts/build_openssl.sh [version]

set -euo pipefail

VERSION="${1:-3.6.2}"
EXPECTED_SHA256="aaf51a1fe064384f811daeaeb4ec4dce7340ec8bd893027eee676af31e83a04f"  # openssl-3.6.2.tar.gz
DEPLOY_TARGET=14.0

ROOT="$(cd "$(dirname "$0")/.." && pwd)"
SRC="$ROOT/src"
TARBALL="$SRC/openssl-$VERSION.tar.gz"
BUILD="$SRC/openssl-$VERSION"
INSTALL="$SRC/openssl-install"

[ -f "$TARBALL" ] || { echo "error: $TARBALL not found (download openssl-$VERSION.tar.gz into src/)"; exit 1; }

echo "==> Verifying tarball checksum"
got="$(shasum -a 256 "$TARBALL" | awk '{print $1}')"
if [ "$got" != "$EXPECTED_SHA256" ]; then
  echo "error: checksum mismatch for $TARBALL"; echo "  expected $EXPECTED_SHA256"; echo "  got      $got"; exit 1
fi

echo "==> Extracting"
rm -rf "$BUILD" "$INSTALL"
tar -C "$SRC" -xzf "$TARBALL"

echo "==> Configuring (macOS arm64, deploy $DEPLOY_TARGET, static PIC, no apps/docs/tests)"
cd "$BUILD"
export MACOSX_DEPLOYMENT_TARGET="$DEPLOY_TARGET"
# no-shared → only libcrypto.a/libssl.a; -fPIC so the static lib can be linked
# into a shared libstrongswan.
./Configure darwin64-arm64-cc \
  --prefix="$INSTALL" \
  --openssldir="$INSTALL/ssl" \
  no-shared no-apps no-docs no-tests \
  "-mmacosx-version-min=$DEPLOY_TARGET" -fPIC

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

echo "==> Installing software (no docs) into $INSTALL"
make install_sw >/dev/null

echo "==> Done:"
ls -la "$INSTALL/lib/"libcrypto.a 2>/dev/null || true
