#!/usr/bin/env bash
# 啟動 Mongo / Redis / MinIO / Mailpit
set -euo pipefail
# shellcheck source=_common.sh
source "$(cd "$(dirname "$0")" && pwd)/_common.sh"

load_env
require_cmd docker

log "starting infra…"
compose up -d

log "waiting for health…"
# mongo
for i in $(seq 1 40); do
  if compose exec -T mongo mongosh --quiet -u "${MONGO_ROOT_USER}" -p "${MONGO_ROOT_PASSWORD}" \
    --authenticationDatabase admin --eval 'db.adminCommand("ping").ok' 2>/dev/null | grep -q 1; then
    log "mongo ok"
    break
  fi
  [[ "$i" -eq 40 ]] && die "mongo not healthy"
  sleep 1
done

# redis
for i in $(seq 1 30); do
  if compose exec -T redis redis-cli -a "${REDIS_PASSWORD}" ping 2>/dev/null | grep -q PONG; then
    log "redis ok"
    break
  fi
  [[ "$i" -eq 30 ]] && die "redis not healthy"
  sleep 1
done

# minio
for i in $(seq 1 30); do
  if curl -sf "http://127.0.0.1:${MINIO_API_PORT:-9000}/minio/health/live" >/dev/null 2>&1; then
    log "minio ok"
    break
  fi
  [[ "$i" -eq 30 ]] && die "minio not healthy"
  sleep 1
done

log "mailpit UI: http://127.0.0.1:${MAILPIT_UI_PORT:-8025}"
log "minio console: http://127.0.0.1:${MINIO_CONSOLE_PORT:-9001}  user=${MINIO_ROOT_USER}"
log "infra up"
