#!/bin/sh
# Build script for libuv (autotools, Template A variant + autogen.sh).
#
# GOTCHA (1b-2): the release tarball ships NO pre-generated `configure`
# (only configure.ac/Makefile.am + autogen.sh) - must autogen before the
# usual libtool-fix + configure steps. Same shape as base/x11vnc's
# autoreconf gotcha.
#
# GOTCHA (1b-2): libuv's configure.ac gates its illumos backend
# (src/unix/sunos.c, `AM_CONDITIONAL([SUNOS], ...)`) on `$host_os` matching
# the literal pattern `solaris*`. Our BUILD_TRIPLE's OS component is
# "hammerhead" (x86_64-zygaena-hammerhead), which doesn't match, so
# unpatched the port silently builds without the SunOS backend at all
# (missing symbols / broken kqueue-less unix core). Patch the
# AM_CONDITIONAL pattern to also match hammerhead* before autogen.sh runs
# (configure.ac -> configure, so this must happen pre-generation, not as
# a `sed` on the generated `configure` like the libtool fix below).
set -e
cd "$SRCDIR"

sed -i -E '/AM_CONDITIONAL\(\[SUNOS\]/ s/\[solaris\*\]/[solaris*|hammerhead*]/' configure.ac

export AUTOCONF=/usr/bin/autoconf
export AUTOHEADER=/usr/bin/autoheader
export ACLOCAL=/usr/bin/aclocal
export AUTOMAKE=/usr/bin/automake
export LIBTOOLIZE=/usr/bin/libtoolize

./autogen.sh

# GOTCHA (1b-2): autogen.sh's libtoolize --install pulls in its OWN fresh
# config.sub/config.guess, which do NOT carry the hammerhead patch (coral's
# pre-build copy is a no-op here since neither file existed in $SRCDIR
# before autogen ran). Re-copy the patched versions now, post-autogen,
# same fix as base/x11vnc.
cp -f /usr/share/autoconf/build-aux/config.sub config.sub 2>/dev/null || true
cp -f /usr/share/autoconf/build-aux/config.guess config.guess 2>/dev/null || true

# MANDATORY libtool fix (Template A): unmatched OS in libtool's
# dynamic-linker case falls through to static-only.
if [ -f configure ]; then
    sed -i -E 's/(kopensolaris\*-gnu)([^)]*\))/\1 | hammerhead*\2/' configure
fi

export PKG_CONFIG_PATH="$PREFIX/lib/pkgconfig:$PREFIX/share/pkgconfig:$PKG_CONFIG_PATH"
export CFLAGS="${CFLAGS} -I$PREFIX/include -D__EXTENSIONS__ -D_POSIX_PTHREAD_SEMANTICS"
export LDFLAGS="${LDFLAGS} -L$PREFIX/lib -R$PREFIX/lib"

./configure \
    --prefix="$PREFIX" \
    --build="$BUILD_TRIPLE" \
    --host="$BUILD_TRIPLE" \
    --sysconfdir="$SYSCONFDIR" \
    --disable-static

gmake -j${JOBS:-1}
gmake install DESTDIR="$PKGDIR"
