#!/bin/bash
set -euo pipefail
BASE_DIR="${GNEXUS_BOOK_PGDATA_ROOT:-$HOME/.local/share/gnexus-book}"
PGDATA="$BASE_DIR/pgdata"
RUNDIR="$BASE_DIR/run"
LOG="$BASE_DIR/postgres.log"
PORT="${GNEXUS_BOOK_PGPORT:-5433}"
DB_USER="${GNEXUS_BOOK_PGUSER:-$(id -un)}"
database_url() {
printf 'postgresql+psycopg://%s@127.0.0.1:%s/gnexus_book\n' "$DB_USER" "$PORT"
}
init_cluster() {
mkdir -p "$BASE_DIR" "$RUNDIR"
if [ ! -s "$PGDATA/PG_VERSION" ]; then
initdb -D "$PGDATA" -U "$DB_USER" --auth-local=trust --auth-host=trust >/dev/null
fi
}
start_cluster() {
init_cluster
if pg_ctl -D "$PGDATA" status >/dev/null 2>&1; then
echo "PostgreSQL already running on port $PORT"
else
pg_ctl -D "$PGDATA" -l "$LOG" \
-o "-p $PORT -k $RUNDIR -c listen_addresses=127.0.0.1" start >/dev/null
for _ in $(seq 1 40); do
pg_isready -h 127.0.0.1 -p "$PORT" -U "$DB_USER" >/dev/null 2>&1 && break
sleep 0.25
done
fi
for db in gnexus_book gnexus_book_test; do
if ! psql -h 127.0.0.1 -p "$PORT" -U "$DB_USER" -d postgres -Atc \
"select 1 from pg_database where datname='$db'" | grep -q 1; then
createdb -h 127.0.0.1 -p "$PORT" -U "$DB_USER" "$db"
fi
done
echo "PostgreSQL is ready: $(database_url)"
}
stop_cluster() {
pg_ctl -D "$PGDATA" stop -m fast
}
case "${1:-status}" in
init)
init_cluster
echo "Initialized $PGDATA"
;;
start)
start_cluster
;;
stop)
stop_cluster
;;
status)
pg_ctl -D "$PGDATA" status
;;
url)
database_url
;;
*)
echo "Usage: $0 {init|start|stop|status|url}" >&2
exit 2
;;
esac