#!/bin/zsh
set -euo pipefail

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

export PATH="/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:$PATH"
if command -v docker >/dev/null 2>&1; then
  if docker info >/dev/null 2>&1; then
    docker compose -f "$REPO_ROOT/docker-compose.timescale.yml" up -d
    exit 0
  fi
fi

if command -v brew >/dev/null 2>&1; then
  brew install postgresql@17 >/dev/null 2>&1 || true
  brew services start postgresql@17
  DB_DSN="${UFORIA_DB_DSN:-postgresql:///uforia?user=$USER}"
  DB_NAME="${DB_DSN##*/}"
  DB_NAME="${DB_NAME%%\?*}"
  if [[ -n "$DB_NAME" ]]; then
    /opt/homebrew/opt/postgresql@17/bin/createdb "$DB_NAME" 2>/dev/null || true
  fi
  /opt/homebrew/opt/postgresql@17/bin/psql -d postgres <<'SQL' >/dev/null 2>&1 || true
ALTER SYSTEM SET checkpoint_timeout = '30min';
ALTER SYSTEM SET checkpoint_completion_target = '0.9';
ALTER SYSTEM SET max_wal_size = '8GB';
ALTER SYSTEM SET wal_compression = 'on';
SQL
  /opt/homebrew/opt/postgresql@17/bin/pg_ctl -D /opt/homebrew/var/postgresql@17 reload >/dev/null 2>&1 || true
  exit 0
fi

echo "Neither Docker nor Homebrew Postgres is available" >&2
exit 1
