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

ROOT_DIR="$(cd "$(dirname "$0")/.." && pwd)"
cd "$ROOT_DIR"

LOCAL_DATABASE_URL_DEFAULT="postgresql://postgres:postgres@127.0.0.1:5432/ballbox_local?schema=public"
LOCAL_DATABASE_URL="${LOCAL_DATABASE_URL:-$LOCAL_DATABASE_URL_DEFAULT}"

is_ready() {
  PGPASSWORD=postgres psql "${LOCAL_DATABASE_URL%%\?*}" -U postgres -c 'select 1;' >/dev/null 2>&1
}

try_docker() {
  if command -v docker >/dev/null 2>&1 || command -v docker-compose >/dev/null 2>&1; then
    ./scripts/docker-compose-local.sh up -d postgres
    return 0
  fi
  return 1
}

try_service() {
  if command -v pg_ctlcluster >/dev/null 2>&1; then
    pg_ctlcluster 17 main start >/dev/null 2>&1 && return 0
    pg_ctlcluster 16 main start >/dev/null 2>&1 && return 0
  fi

  if command -v systemctl >/dev/null 2>&1; then
    systemctl start postgresql >/dev/null 2>&1 && return 0
    systemctl --user start postgresql >/dev/null 2>&1 && return 0
  fi

  if command -v service >/dev/null 2>&1; then
    service postgresql start >/dev/null 2>&1 && return 0
  fi

  return 1
}

if is_ready; then
  echo "Local Postgres already ready."
  exit 0
fi

if try_docker; then
  for _ in $(seq 1 30); do
    if is_ready; then
      echo "Local Postgres started via Docker."
      exit 0
    fi
    sleep 2
  done
  echo "Docker started but local Postgres did not become ready in time."
  exit 1
fi

if try_service; then
  for _ in $(seq 1 30); do
    if is_ready; then
      echo "Local Postgres started outside Docker."
      exit 0
    fi
    sleep 2
  done
  echo "Postgres start command ran but local Postgres did not become ready in time."
  exit 1
fi

echo "Could not start local Postgres automatically."
echo "Tried: docker compose, docker-compose, pg_ctlcluster, systemctl, service."
echo "Start a local Postgres that serves: ${LOCAL_DATABASE_URL%%\?*}"
exit 1
