#!/bin/bash
set -e

: "${PKG_CONFIG_PATH:=/usr/local/lib/pkgconfig}"
export PKG_CONFIG_PATH

CFLAGS=$(pkg-config --cflags libvalhalla)
LIBS=$(pkg-config --libs libvalhalla)
LIBDIR=$(pkg-config --variable=libdir libvalhalla)
CURL_LIBS=$(pkg-config --libs libcurl 2>/dev/null || echo -lcurl)

# Valhalla's cmake install writes a broken libvalhalla.dylib symlink on macOS
# (points at libvalhalla.dylib.3 instead of libvalhalla.3.dylib). Left alone,
# -lvalhalla silently falls back to the stale libvalhalla.a and produces
# confusing protobuf-ABI link errors. Repair it if we can find the real target.
DYLIB="$LIBDIR/libvalhalla.dylib"
if [ ! -e "$DYLIB" ]; then
    REAL=$(ls "$LIBDIR"/libvalhalla.*.dylib 2>/dev/null | head -1)
    if [ -z "$REAL" ]; then
        echo "error: no libvalhalla.*.dylib found in $LIBDIR" >&2
        exit 1
    fi
    echo "repairing $DYLIB -> $(basename "$REAL")"
    ln -sf "$(basename "$REAL")" "$DYLIB" 2>/dev/null \
        || sudo ln -sf "$(basename "$REAL")" "$DYLIB"
fi

clang++ -std=c++20 \
    -dynamiclib \
    -o libvalhalla_c.dylib \
    valhalla_c_api.cpp \
    $CFLAGS \
    -I/opt/homebrew/include \
    $LIBS \
    $CURL_LIBS \
    -L/opt/homebrew/lib \
    -Wl,-rpath,"$LIBDIR" \
    -Wl,-rpath,/opt/homebrew/lib

echo "Built libvalhalla_c.dylib"
