#!/usr/bin/env bash
# Stack-task entrypoint shim: source the host-rendered secrets env, then hand
# off to the image's real entrypoint.
#
# Why: `docker stack deploy` does not support compose's `env_file:`, and
# enumerating every vault key in the stack yml's `environment:` blocks would
# drift the moment a key is added to deploy/secrets/. Instead deploy-stack.sh
# installs a uid-10001-readable copy of the rendered env at
# /etc/thermograph/stack.env, the stack bind-mounts it (with this script) into
# every app task, and this shim exports each KEY=value — but ONLY for keys not
# already set, so the yml's `environment:` blocks keep compose's env_file
# precedence (environment always wins). Same set-if-unset contract as the
# image's own /run/secrets shim in deploy/entrypoint.sh, which still runs
# after this and stays a no-op here.
set -euo pipefail

ENV_FILE="${THERMOGRAPH_HOST_ENV:-/host/thermograph.env}"

if [ -f "$ENV_FILE" ]; then
  while IFS= read -r line || [ -n "$line" ]; do
    case "$line" in
      ''|'#'*) continue ;;
      *=*)
        key="${line%%=*}"
        # Only sane identifiers; only if not already set by `environment:`.
        case "$key" in
          *[!A-Za-z0-9_]*|'') continue ;;
        esac
        if [ -z "${!key:-}" ]; then
          export "$key=${line#*=}"
        fi
        ;;
    esac
  done < "$ENV_FILE"
fi

# Hand off: the backend image has a real entrypoint script and takes that
# branch. Anything else needs an explicit `command:` in the stack yml's
# service block -- overriding `entrypoint:` here drops the image's own CMD
# entirely (Docker/Swarm does not merge them), so `$@` is empty unless the
# stack file supplies one. The frontend service does exactly that. The
# uvicorn fallback below is what ran, silently, whenever that expectation
# didn't hold; it is Python-specific and kept only as a loud, familiar-looking
# failure for a misconfigured non-Python image, not a real handoff path.
if [ -x /app/deploy/entrypoint.sh ]; then
  exec /app/deploy/entrypoint.sh "$@"
elif [ "$#" -gt 0 ]; then
  exec "$@"
else
  exec uvicorn app:app --host 0.0.0.0 --port "${PORT:-8080}"
fi
