#!/bin/sh
set -e

# NOTE: to be removed once no longer used in https://github.com/python/buildmaster-config/blob/main/master/custom/factories.py ;
#       expected in Python 3.18 as 3.13 is when `wasi.py` was introduced.

# function
usage() {
    echo "wasi-env - Run command with WASI-SDK"
    echo ""
    echo "wasi-env is a helper to set various environment variables to"
    echo "run configure and make with WASI-SDK. A WASI-SDK must be either"
    echo "installed at /opt/wasi-sdk or the env var 'WASI_SDK_PATH' must"
    echo "set to the root of a WASI-SDK."
    echo ""
    echo "Usage: wasi-env command [...]"
    echo ""
    echo "    -h --help     display this help and exit"
    echo ""
}

case $1 in
    -h|--help)
        usage
        exit
        ;;
esac

if test -z "$1"; then
    echo "ERROR: command required" >&2
    usage
    exit 1
fi

WASI_SDK_PATH="${WASI_SDK_PATH:-/opt/wasi-sdk}"
WASI_SYSROOT="${WASI_SDK_PATH}/share/wasi-sysroot"

if ! test -x "${WASI_SDK_PATH}/bin/clang"; then
    echo "Error: ${WASI_SDK_PATH}/bin/clang does not exist." >&2
    exit 2
fi

CC="${WASI_SDK_PATH}/bin/clang"
CPP="${WASI_SDK_PATH}/bin/clang-cpp"
CXX="${WASI_SDK_PATH}/bin/clang++"

# --sysroot is required if WASI-SDK is not installed in /opt/wasi-sdk.
if test "${WASI_SDK_PATH}" != "/opt/wasi-sdk"; then
    CC="${CC} --sysroot=${WASI_SYSROOT}"
    CPP="${CPP} --sysroot=${WASI_SYSROOT}"
    CXX="${CXX} --sysroot=${WASI_SYSROOT}"
fi

# use ccache if available
if command -v ccache >/dev/null 2>&1; then
    CC="ccache ${CC}"
    CPP="ccache ${CPP}"
    CXX="ccache ${CXX}"
fi

AR="${WASI_SDK_PATH}/bin/llvm-ar"
RANLIB="${WASI_SDK_PATH}/bin/ranlib"

# instruct pkg-config to use sysroot
PKG_CONFIG_PATH=""
PKG_CONFIG_LIBDIR="${WASI_SYSROOT}/lib/pkgconfig:${WASI_SYSROOT}/share/pkgconfig"
PKG_CONFIG_SYSROOT_DIR="${WASI_SYSROOT}"

PATH="${WASI_SDK_PATH}/bin:${PATH}"

export WASI_SDK_PATH WASI_SYSROOT
export CC CPP CXX LDSHARED AR RANLIB
export CFLAGS LDFLAGS
export PKG_CONFIG_PATH PKG_CONFIG_LIBDIR PKG_CONFIG_SYSROOT_DIR
export PATH

# no exec, it makes argv[0] path absolute.
"$@"
