#!/bin/sh
set -eu

runtime_config=$(jq -cn \
  --arg mapboxAccessToken "${TJWATER_MAPBOX_ACCESS_TOKEN:-}" \
  --arg mapUrl "${TJWATER_MAP_URL:-https://geoserver.waternetwork.cn/geoserver}" \
  --arg geoserverWorkspace "${TJWATER_GEOSERVER_WORKSPACE:-tjwater}" \
  --arg agentApiBaseUrl "${TJWATER_AGENT_API_BASE_URL:-http://127.0.0.1:8787}" \
  --arg enableDevPanel "${TJWATER_ENABLE_DEV_PANEL:-false}" \
  --arg enableMsw "${TJWATER_ENABLE_MSW:-false}" \
  '{
    TJWATER_MAPBOX_ACCESS_TOKEN: $mapboxAccessToken,
    TJWATER_MAP_URL: $mapUrl,
    TJWATER_GEOSERVER_WORKSPACE: $geoserverWorkspace,
    TJWATER_AGENT_API_BASE_URL: $agentApiBaseUrl,
    TJWATER_ENABLE_DEV_PANEL: $enableDevPanel,
    TJWATER_ENABLE_MSW: $enableMsw
  }')

printf 'globalThis.__TJWATER_CONFIG__ = %s;\n' "$runtime_config" > /srv/runtime-config.js

node /usr/local/lib/tjwater-frontend/edge-tts-server.cjs &
tts_pid=$!

"$@" &
app_pid=$!

terminate() {
  kill "$app_pid" "$tts_pid" 2>/dev/null || true
}
trap terminate INT TERM

status=0
wait -n "$app_pid" "$tts_pid" || status=$?
terminate
wait "$app_pid" 2>/dev/null || true
wait "$tts_pid" 2>/dev/null || true
exit "$status"
