#!/usr/bin/env bash
set -euo pipefail

ROOT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/.." && pwd)"
COMPOSE_FILE="$ROOT_DIR/docker/compose.yml"
ENVIRONMENT="${1:-staging}"
if [[ "$ENVIRONMENT" == dev || "$ENVIRONMENT" == staging ]]; then shift || true; else ENVIRONMENT=staging; fi

ENV_FILE="${CI_ENV_FILE:-}"
cleanup() { [[ -n "$ENV_FILE" && "$ENV_FILE" != "${CI_ENV_FILE:-}" ]] && rm -f "$ENV_FILE" || true; }
trap cleanup EXIT
if [[ -z "$ENV_FILE" && -z "${CI:-}" ]]; then
  ENV_FILE="$(mktemp "${TMPDIR:-/tmp}/spoon-compose.XXXXXX.env")"
  sh "$ROOT_DIR/scripts/export-env" "$ENVIRONMENT" > "$ENV_FILE"
fi

args=()
[[ -z "$ENV_FILE" ]] || args+=(--env-file "$ENV_FILE")
translated=()
for arg in "$@"; do
  case "$arg" in backend) translated+=(spoon-backend) ;; dashboard) translated+=(spoon-dashboard) ;; next) translated+=(spoon-next) ;; *) translated+=("$arg") ;; esac
done
set +e
docker compose "${args[@]}" -f "$COMPOSE_FILE" "${translated[@]}"
status=$?
set -e
exit "$status"
