#!/bin/bash
#
# build_dnsmasq.sh — build dnsmasq from src/dnsmasq-<ver>.tar.gz for macOS 14.0.
# dnsmasq is bundled as a standalone binary (no dylib dependencies); SwanDesk
# launches it on VPN connect to provide a local DNS proxy on 127.0.0.1:53,
# enabling split-DNS and per-domain forwarding rules.
#
# Output: src/dnsmasq-install/sbin/dnsmasq — consumed by stage_strongswan.sh.
#
# Usage: Scripts/build_dnsmasq.sh [version]

set -euo pipefail

VERSION="${1:-2.90}"
EXPECTED_SHA256="8f6666b542403b5ee7ccce66ea73a4a51cf19dd49392aaccd37231a2c51b303b"  # dnsmasq-2.90.tar.gz
DEPLOY_TARGET=14.0

ROOT="$(cd "$(dirname "$0")/.." && pwd)"
SRC="$ROOT/src"
TARBALL="$SRC/dnsmasq-$VERSION.tar.gz"
BUILD="$SRC/dnsmasq-$VERSION"
INSTALL="$SRC/dnsmasq-install"
DOWNLOAD_URL="https://www.thekelleys.org.uk/dnsmasq/dnsmasq-$VERSION.tar.gz"

if [ ! -f "$TARBALL" ]; then
  echo "==> Downloading dnsmasq $VERSION"
  curl -fL "$DOWNLOAD_URL" -o "$TARBALL"
fi

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"

mkdir -p "$INSTALL/sbin"

echo "==> Building dnsmasq $VERSION (macOS $DEPLOY_TARGET)"
cd "$BUILD"
make -j"$(sysctl -n hw.ncpu)" \
  CC=clang \
  COPTS="-mmacosx-version-min=$DEPLOY_TARGET -Os" \
  LDFLAGS="-mmacosx-version-min=$DEPLOY_TARGET" \
  PREFIX="$INSTALL"

cp src/dnsmasq "$INSTALL/sbin/dnsmasq"
chmod 755 "$INSTALL/sbin/dnsmasq"

echo "==> Done:"
ls -la "$INSTALL/sbin/dnsmasq"
