#!/usr/bin/env bash
set -e

# Directory for the new cluster
PGDATA="/tmp/pgcluster"

# Ensure directory is clean
rm -rf "$PGDATA"
mkdir -p "$PGDATA"

echo "Initializing PostgreSQL cluster at $PGDATA"
initdb -D "$PGDATA" -U postgres

# Start the server
pg_ctl -D "$PGDATA" -l "$PGDATA"/logfile start -w

echo "creating test tables"
psql -U postgres -d postgres -c "CREATE TABLE t(id int, val int DEFAULT 0)"
psql -U postgres -d postgres -c "INSERT INTO t(id, val) VALUES (1, 1), (2, 2), (3, 3)"

# Generate a large number of multixact IDs via python script
python3 "$(dirname "$0")/generate_multixids.py" 100000

psql -U postgres -d postgres -c "update pg_database set datallowconn =true where datname='template0';"
vacuumdb -U postgres -a --freeze --min-mxid-age=1
psql -U postgres -d postgres -c "checkpoint"
psql -U postgres -d postgres -c "update pg_database set datallowconn =false where datname='template0';"

python3 "$(dirname "$0")/generate_multixids.py" 10000

echo "Shutting down PostgreSQL"
pg_ctl -D "$PGDATA" stop

next_multixid=$(pg_controldata "$PGDATA" | awk '/NextMultiXactId:/ {print $4}')
echo "NEXT: $next_multixid"
pg_resetwal -D "$PGDATA" -m "$next_multixid,1"

echo "Done."
