#!/usr/bin/env bash
#
# blame(jens)
#
# Serves one of the apps in this workspace.
#
# Usage: ./run.sh <project> [profile] [extra nx options...]
#
#   project   cloud-ziti (cz) or nfconsole (nf). Required.
#   profile   build configuration, defaults to "localhost".
#
# Extra options pass through to nx serve, so both apps can run at once:
#   ./run.sh cz
#   ./run.sh nf localhost --port=4300

set -e          # raise exception if error
set -u          # raise exception if unset
set -o pipefail # raise exceptions in pipes

BASENAME=$(basename "$0")
WORKDIR=$(cd "$(dirname "$0")"; pwd -P;)
cd "$WORKDIR"

usage() {
    echo "usage: ${BASENAME} <cloud-ziti|cz|nfconsole|nf> [profile] [extra nx options...]" >&2
}

if [[ $# -lt 1 ]]; then
    echo "${BASENAME}: no project given" >&2
    usage
    exit 2
fi

# Lower case with tr, not ${1,,}, so the script still runs on bash 3.2.
case "$(echo "$1" | tr '[:upper:]' '[:lower:]')" in
    cloud-ziti|cz)
        PROJECT="cloud-ziti"
        ;;
    nfconsole|nf)
        PROJECT="nfconsole"
        ;;
    -h|--help)
        usage
        exit 0
        ;;
    *)
        echo "${BASENAME}: unknown project '$1'" >&2
        usage
        exit 2
        ;;
esac
shift

profile="localhost"
if [[ $# -gt 0 ]]; then
    profile=$1
    shift
fi

export NODE_OPTIONS=--max_old_space_size=12288

# This is a yarn 4 workspace. npm install ignores the resolutions block that pins
# the nx native binaries and leaves node_modules broken, so always install with yarn.
# --immutable fails loudly instead of drifting yarn.lock on a floating range.
yarn install --immutable

# Nx copies its native .node binary to a temp dir keyed on the workspace path and
# the JS nx version, never on the binary. A stale copy survives a correct reinstall
# and dies with a rust type conversion error. Drop it before serving.
native_cache=$(node -p "require('./node_modules/nx/src/native/native-file-cache-location').getNativeFileCacheLocation()" 2>/dev/null || true)
if [[ -n "$native_cache" && "$native_cache" == */nx-native-file-cache-* ]]; then
    rm -rf "$native_cache"
fi

echo "${BASENAME}: serving ${PROJECT} with the ${profile} profile" >&2

# Call the workspace nx. A global nx on PATH can be a different major version.
exec node_modules/.bin/nx serve "$PROJECT" --configuration="$profile" "$@"
