#!/bin/sh
set -eu

ROOT=$(CDPATH='' cd -- "$(dirname -- "$0")/.." && pwd)
cd "$ROOT"
ENV_FILE=${1:-"$ROOT/.env"}

case "$ENV_FILE" in
  /*) ;;
  *) ENV_FILE="$ROOT/$ENV_FILE" ;;
esac

if [ ! -f "$ENV_FILE" ]; then
  echo "Deployment environment does not exist: $ENV_FILE" >&2
  exit 1
fi

read_env_value() {
  key=$1

  awk -v key="$key" '
    index($0, key "=") == 1 {
      print substr($0, length(key) + 2)
      found = 1
      exit
    }
    END { if (!found) exit 1 }
  ' "$ENV_FILE"
}

DATABASE_MODE=$(read_env_value DATABASE_MODE 2>/dev/null || printf container)
COMPOSE_PROJECT_NAME=$(read_env_value COMPOSE_PROJECT_NAME 2>/dev/null || printf who_need_help)
export COMPOSE_PROJECT_NAME

CODEX_SESSION_ID=${CODEX_SESSION_ID:-${CODEX_THREAD_ID:-not-configured}}
export CODEX_SESSION_ID

if [ "$DATABASE_MODE" = external ]; then
  "$ROOT/scripts/compose.sh" "$ENV_FILE" build migrate
  "$ROOT/scripts/check-database.sh" "$ENV_FILE"
fi

"$ROOT/scripts/compose.sh" "$ENV_FILE" up -d --build --wait --remove-orphans
"$ROOT/scripts/verify-realtime-cluster.sh" compose
"$ROOT/scripts/verify-beam-runtime.sh" compose
