#!/bin/sh
# Build script for xdm (autotools, Template A).
#
# xdm authenticates via PAM (illumos <security/pam_appl.h> + -lpam, both in
# base). configure autodetects PAM but we pass --with-pam to make it a hard
# requirement (fail loudly rather than silently building a crypt(3)-only xdm).
#
# XDMCP: no --without-xdmcp exists in 1.1.17 (PKG_CHECK_MODULES(DMCP, xdmcp)
# is unconditional). The UDP listener is disabled at runtime instead via the
# shipped config's `DisplayManager.requestPort: 0` (see package.toml).
#
# Patches (patches/, applied -p1 below): illumos portability fixes discovered
# during the alpha10 build. See each patch header for the specific reason.
set -e

# Resolve the port dir (holds patches/) BEFORE cd'ing into the extracted source.
PORTDIR=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)

cd "$SRCDIR"

# --- Hammerhead/illumos portability patches ---
# coral runs this script under zsh; an unmatched glob is a hard error there,
# so enable NULL_GLOB (empty expansion) when running under zsh. The [ -f ]
# guard covers the /bin/sh case (glob stays literal).
if [ -n "$ZSH_VERSION" ]; then setopt NULL_GLOB 2>/dev/null || true; fi
for p in "$PORTDIR"/patches/*.patch; do
    [ -f "$p" ] || continue
    echo "==> Applying patch: $(basename "$p")"
    patch -p1 < "$p"
done

# MANDATORY libtool fix (Task 4a): this release's libtool-generated
# `configure` has no illumos/hammerhead arm in its dynamic-linker detection
# `case $host_os in ...` block; unmatched OS falls through to
# `*) dynamic_linker=no ;;` forcing static-only. Piggyback hammerhead onto
# the kopensolaris arm.
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 \
    --with-pam \
    --with-xdmconfigdir="$PREFIX/lib/X11/xdm"

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