#!/bin/bash

# Exit on error
set -e

echo "🛑 Stopping any existing Postgres instance..."
pg_ctl -D ./sandbox_data stop -m fast 2>/dev/null || true

echo "🧹 Cleaning up old sandbox data..."
rm -rf ./sandbox_data

echo "🌱 Initializing new cluster for Destruction Labs..."
# Use postgres@16 path if installed via brew
export PATH="/opt/homebrew/opt/postgresql@16/bin:$PATH"
export PATH="/usr/local/opt/postgresql@16/bin:$PATH" # Intel Mac fallback

export LC_ALL="en_US.UTF-8"
export LANG="en_US.UTF-8"

initdb --locale=en_US.UTF-8 -E UTF-8 -D ./sandbox_data

echo "⚙️ Applying severe memory constraints to postgresql.conf..."
cat <<EOT >> ./sandbox_data/postgresql.conf

# --- DESTRUCTION LABS CONSTRAINTS ---
shared_buffers = 16MB          # Tiny cache, forces disk reads
work_mem = 4MB                 # Forces sorts/hashes to spill to disk
maintenance_work_mem = 8MB     # Makes Vacuum struggle
max_connections = 100          # For queueing simulation
log_min_duration_statement = 0 # Log all queries for analysis
EOT

echo "🚀 Starting constrained PostgreSQL..."
pg_ctl -D ./sandbox_data -l ./sandbox_data/logfile start

echo "⏳ Waiting for Postgres to be ready..."
sleep 2

# Find the main postgres process ID (Postmaster)
POSTGRES_PID=$(head -n 1 ./sandbox_data/postmaster.pid)

if [ -z "$POSTGRES_PID" ]; then
    echo "❌ Failed to find Postgres PID."
    exit 1
fi

echo "⛓️ Applying cpulimit (10% of a single core) to Postgres process ($POSTGRES_PID)..."
# Run cpulimit in the background detached
nohup cpulimit -p $POSTGRES_PID -l 10 > /dev/null 2>&1 &

echo "✅ Sandbox is ready!"
echo "Connect using: psql -d postgres"
