#!/usr/bin/env bash
#
# Run the customer-connect-console dev server against a chosen backend.
#
# Usage:
#   ./run.sh                  # defaults to localhost (backend on :8080)
#   ./run.sh sandbox          # points at gateway.sandbox.netfoundry.io
#   ./run.sh staging          # points at gateway.staging.netfoundry.io
#   ./run.sh local-connect    # HTTPS dev server with wildcard subdomains
#   ./run.sh staging --port 4300
#
# Anything after the profile is passed through to `ng serve`.

set -euo pipefail

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

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

case "$profile" in
  localhost|sandbox|staging|local-connect|development) ;;
  *)
    echo "ERROR: unknown profile '$profile'" >&2
    echo "       known profiles: localhost, sandbox, staging, local-connect, development" >&2
    exit 1
    ;;
esac

if [[ ! -d node_modules ]]; then
  echo ">> node_modules missing — running npm install"
  npm install
fi

export NODE_OPTIONS=${NODE_OPTIONS:-"--max_old_space_size=8192"}

echo ">> ng serve --configuration=$profile $*"
exec npx ng serve --configuration="$profile" "$@"
