#!/bin/bash
set -e

ENV_FILE="/shared/.env"
MAX_WAIT=60
WAITED=0

# 安全のため .env が削除される（clean_up完了）のを待つ
while [ -f "$ENV_FILE" ]; do
  if [ $WAITED -ge $MAX_WAIT ]; then
    echo "ERROR: Timed out waiting for $ENV_FILE to be removed by clean_up"
    exit 1
  fi
  echo "Waiting for clean_up to remove $ENV_FILE..."
  sleep 2
  WAITED=$((WAITED + 2))
done

# 削除確認後、再作成を待つ
WAITED=0
while ! grep -q "MANAGEMENT_USER_POOL_ID=" "$ENV_FILE" 2>/dev/null; do
  if [ $WAITED -ge $MAX_WAIT ]; then
    echo "ERROR: Timed out waiting for MANAGEMENT_USER_POOL_ID in $ENV_FILE"
    exit 1
  fi
  echo "Waiting for MANAGEMENT_USER_POOL_ID to be set in $ENV_FILE..."
  sleep 2
  WAITED=$((WAITED + 2))
done


set -a
source "$ENV_FILE"
set +a

exec uvicorn "$@"
