#!/bin/bash
# Build-only pg_config wrapper for compiling extensions against a
# DESTDIR-staged private PostgreSQL installation.  Header, library, and PGXS
# lookups must resolve inside the stage, while installation directories must
# remain rooted at the final /usr/pgtde-18 prefix so a later DESTDIR is not
# duplicated.  The packaged pg_config remains untouched.
set -e

: "${PGTDE_STAGE:?PGTDE_STAGE must point to the staged PostgreSQL root}"
prefix=/usr/pgtde-18
real_pg_config="${PGTDE_STAGE}${prefix}/bin/pg_config"

output=$("${real_pg_config}" "$@")
# PostgreSQL's pg_config is relocatable and therefore reports the stage prefix
# when invoked from the staged tree. Normalize it before selecting build or
# installation semantics below.
normalized="${output//${PGTDE_STAGE}${prefix}/${prefix}}"
mode="${PGTDE_PG_CONFIG_MODE:-hybrid}"
if [[ "${mode}" == stage ]]; then
  printf '%s\n' "${normalized//${prefix}/${PGTDE_STAGE}${prefix}}"
  exit 0
fi
if [[ "${mode}" == final ]]; then
  printf '%s\n' "${normalized}"
  exit 0
fi
case "${1:-}" in
  --includedir|--includedir-server|--libdir|--pkgincludedir|--pgxs)
    printf '%s\n' "${normalized//${prefix}/${PGTDE_STAGE}${prefix}}"
    ;;
  --ldflags|--ldflags_ex|--ldflags_sl)
    printf '%s\n' "${normalized}" | sed "s|-L${prefix}|-L${PGTDE_STAGE}${prefix}|g"
    ;;
  *)
    printf '%s\n' "${normalized}"
    ;;
esac
