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

ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
PG_BIN="/usr/lib/postgresql/17/bin"
if [ -d "/Library/PostgreSQL/18/bin" ]; then
  PG_BIN="/Library/PostgreSQL/18/bin"
elif [ -d "/Library/PostgreSQL/17/bin" ]; then
  PG_BIN="/Library/PostgreSQL/17/bin"
fi
PG_DATA="$ROOT_DIR/.local/postgres"
PG_LOG="$ROOT_DIR/.local/postgres.log"
PG_PORT="${PGPORT:-55432}"
PG_SOCKET_DIR="$ROOT_DIR/.local"

if [ ! -d "$PG_DATA" ]; then
  "$PG_BIN/initdb" -D "$PG_DATA" -U rentx --auth=trust
fi

if ! "$PG_BIN/pg_ctl" -D "$PG_DATA" status >/dev/null 2>&1; then
  "$PG_BIN/pg_ctl" -D "$PG_DATA" -l "$PG_LOG" -o "-p $PG_PORT -k $PG_SOCKET_DIR" start
fi

"$PG_BIN/createdb" -h localhost -p "$PG_PORT" -U rentx rentx 2>/dev/null || true

echo "PostgreSQL local iniciado em localhost:$PG_PORT"
