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

root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
compose_file="$root/deployments/local/docker-compose.yml"

database_url="${DATABASE_URL:-postgres://alt:alt@localhost:15430/alt?sslmode=disable}"
redis_url="${REDIS_URL:-redis://localhost:16330/0}"

docker_cmd=""
if command -v docker >/dev/null 2>&1; then
  docker_cmd="$(command -v docker)"
elif [ -x "/Applications/Docker.app/Contents/Resources/bin/docker" ]; then
  docker_cmd="/Applications/Docker.app/Contents/Resources/bin/docker"
fi

check_default_postgres() {
  if [ -z "$docker_cmd" ]; then
    echo "postgres: docker is unavailable; cannot inspect local compose service" >&2
    return 1
  fi
  "$docker_cmd" compose -f "$compose_file" exec -T postgres pg_isready -U alt -d alt
}

check_default_redis() {
  if [ -z "$docker_cmd" ]; then
    echo "redis: docker is unavailable; cannot inspect local compose service" >&2
    return 1
  fi
  test "$("$docker_cmd" compose -f "$compose_file" exec -T redis redis-cli ping)" = "PONG"
}

check_external_postgres() {
  if command -v pg_isready >/dev/null 2>&1; then
    pg_isready -d "$database_url"
    return
  fi
  echo "postgres: pg_isready is required when DATABASE_URL overrides local compose" >&2
  return 1
}

check_external_redis() {
  if command -v redis-cli >/dev/null 2>&1; then
    test "$(redis-cli -u "$redis_url" ping)" = "PONG"
    return
  fi
  echo "redis: redis-cli is required when REDIS_URL overrides local compose" >&2
  return 1
}

echo "ALT infrastructure health"

if [ "$database_url" = "postgres://alt:alt@localhost:15430/alt?sslmode=disable" ]; then
  check_default_postgres
else
  check_external_postgres
fi
echo "postgres: ok"

if [ "$redis_url" = "redis://localhost:16330/0" ]; then
  check_default_redis
else
  check_external_redis
fi
echo "redis: ok"
