#!/usr/bin/env sh
set -eu

if [ "$#" -eq 0 ]; then
  echo "Usage: $0 <service> [service ...]" >&2
  exit 2
fi

compose_files="${CI_DOCKER_COMPOSE_FILES:--f docker-compose.yml -f .github/docker-compose.ci.yml}"
lock_file="${CI_DOCKER_LOCK_FILE:-/tmp/pleno-api-ci-docker-compose-up.lock}"
max_attempts="${CI_DOCKER_UP_RETRIES:-${PHP_CI_DOCKER_RETRIES:-3}}"
export COMPOSE_PROFILES="${COMPOSE_PROFILES:-dev}"

compose_up() {
  attempt=1
  while :; do
    docker network prune -f >/dev/null 2>&1 || true

    if docker compose $compose_files up -d "$@"; then
      return 0
    fi

    status="$?"
    docker compose $compose_files down -v --remove-orphans >/dev/null 2>&1 || true

    if [ "$attempt" -ge "$max_attempts" ]; then
      return "$status"
    fi

    sleep_seconds=$((attempt * 5))
    echo "Docker compose up failed with status $status; retrying in ${sleep_seconds}s (attempt $((attempt + 1))/$max_attempts)." >&2
    sleep "$sleep_seconds"
    attempt=$((attempt + 1))
  done
}

if command -v flock >/dev/null 2>&1; then
  (
    flock 9
    compose_up "$@"
  ) 9>"$lock_file"
else
  echo "flock is not available; running Docker compose startup without a host lock." >&2
  compose_up "$@"
fi
