#!/bin/bash
# PostgreSQL 18.3 - build from source
# Usage: bash scripts/setup/01_postgresql.sh

set -euo pipefail

PG_VERSION="18.3"
PG_SOURCE_URL="https://ftp.postgresql.org/pub/source/v${PG_VERSION}/postgresql-${PG_VERSION}.tar.gz"
PG_PREFIX="$HOME/pgsql/${PG_VERSION}"
PG_DATA="$HOME/pgsql/data"

echo "=== PostgreSQL ${PG_VERSION} Source Build ==="

# Step 1: Install build deps (via Homebrew)
echo "[1/5] Installing build dependencies..."
brew install readline zlib icu4c openssl e2fsprogs pkg-config

# Step 2: Download source
echo "[2/5] Downloading PostgreSQL ${PG_VERSION} source..."
mkdir -p ~/momentry_core_0.1/services/postgresql
cd ~/momentry_core_0.1/services/postgresql
curl -sL "$PG_SOURCE_URL" -o "postgresql-${PG_VERSION}.tar.gz"
tar xzf "postgresql-${PG_VERSION}.tar.gz"
cd "postgresql-${PG_VERSION}"

# Step 3: Configure
echo "[3/5] Configuring..."
export PKG_CONFIG_PATH="/opt/homebrew/opt/zlib/lib/pkgconfig:/opt/homebrew/opt/readline/lib/pkgconfig:/opt/homebrew/opt/icu4c/lib/pkgconfig:/opt/homebrew/lib/pkgconfig"
export LDFLAGS="-L/opt/homebrew/opt/openssl/lib"
export CPPFLAGS="-I/opt/homebrew/opt/openssl/include"
./configure --prefix="$PG_PREFIX" --with-uuid=e2fs --with-icu --with-openssl

# Step 4: Build
echo "[4/5] Building (parallel)..."
CORES=$(sysctl -n hw.ncpu)
make -j$CORES
make install

# Step 5: Initialize data directory
echo "[5/5] Initializing data directory..."
mkdir -p "$PG_DATA"
"$PG_PREFIX/bin/initdb" -D "$PG_DATA"

# Record checksum
echo "PostgreSQL SHA256: $(shasum -a 256 "$PG_PREFIX/bin/postgres" | cut -d' ' -f1)"
echo "=== PostgreSQL ${PG_VERSION} build complete ==="
echo "Start: pg_ctl -D $PG_DATA -l $HOME/pgsql/pg.log start"
