#!/usr/bin/env bash
set -euo pipefail

# Build wpa_supplicant for ARM toolchain with nl80211/libnl from sysroot.
#
# Usage:
#   ./build.sh [SYSROOT]
#
# Example:
#   ./build.sh /home/stargazer/arm-uclinuxfdpiceabi/sysroot

TOOLCHAIN_PREFIX="${TOOLCHAIN_PREFIX:-arm-uclinuxfdpiceabi}"
CC_BIN="${CC_BIN:-${TOOLCHAIN_PREFIX}-gcc}"
JOBS="${JOBS:-$(nproc)}"

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
WPA_DIR="${SCRIPT_DIR}/wpa_supplicant"
SYSROOT_DEFAULT="/home/stargazer/arm-uclinuxfdpiceabi/sysroot"
SYSROOT="${1:-${SYSROOT:-$SYSROOT_DEFAULT}}"

PKGCFG_LIBDIR_CANDIDATES=(
  "${SYSROOT}/usr/lib/pkgconfig"
  "${SYSROOT}/usr/lib64/pkgconfig"
  "${SYSROOT}/usr/share/pkgconfig"
)

die() {
  echo "ERROR: $*" >&2
  exit 1
}

if ! command -v "${CC_BIN}" >/dev/null 2>&1; then
  die "Compiler not found in PATH: ${CC_BIN}"
fi

if [ ! -d "${WPA_DIR}" ]; then
  die "wpa_supplicant directory not found: ${WPA_DIR}"
fi

if [ ! -d "${SYSROOT}" ]; then
  die "SYSROOT not found: ${SYSROOT}"
fi

PKG_CONFIG_LIBDIR=""
for d in "${PKGCFG_LIBDIR_CANDIDATES[@]}"; do
  if [ -d "${d}" ]; then
    if [ -z "${PKG_CONFIG_LIBDIR}" ]; then
      PKG_CONFIG_LIBDIR="${d}"
    else
      PKG_CONFIG_LIBDIR="${PKG_CONFIG_LIBDIR}:${d}"
    fi
  fi
done

if [ -z "${PKG_CONFIG_LIBDIR}" ]; then
  die "No pkg-config directories found in SYSROOT"
fi

export PKG_CONFIG_SYSROOT_DIR="${SYSROOT}"
export PKG_CONFIG_LIBDIR
unset PKG_CONFIG_PATH

if ! pkg-config --exists libnl-3.0; then
  die "libnl-3.0.pc not found via pkg-config. Checked: ${PKG_CONFIG_LIBDIR}"
fi

if ! pkg-config --exists libnl-genl-3.0; then
  die "libnl-genl-3.0.pc not found via pkg-config. Checked: ${PKG_CONFIG_LIBDIR}"
fi

echo "Compiler: ${CC_BIN}"
echo "SYSROOT: ${SYSROOT}"
echo "PKG_CONFIG_LIBDIR: ${PKG_CONFIG_LIBDIR}"
echo "libnl-3.0 version: $(pkg-config --modversion libnl-3.0)"
echo "libnl-genl-3.0 version: $(pkg-config --modversion libnl-genl-3.0)"

cd "${WPA_DIR}"
make clean
make -j"${JOBS}" CC="${CC_BIN}"

echo "Build completed successfully."
