#!/bin/bash

set -e  # Exit on any error

# Define PostgreSQL parameters
PGDATA="/home/ajin/dataoss"  # Adjust based on your setup
PGDATA2="/home/ajin/dataoss2"
PG_SLOT_DIR="$PGDATA/pg_replslot/mysub"
PUB_PORT=5432
SUB_PORT=5433
REPL_USER="replicator"
DB_NAME="testdb"

# Start PostgreSQL instances if not already running
pg_ctl restart -D "$PGDATA" -l "$PGDATA/logfile" || echo "PostgreSQL already running"
pg_ctl restart -D "$PGDATA2" -l "$PGDATA2/logfile" || echo "PostgreSQL already running"

# Setup the publisher database
psql -p $PUB_PORT postgres -c "CREATE TABLE tbl_pub(id int, val1 text, val2 text, val3 text);"
psql -p $PUB_PORT postgres -c "CREATE TABLE tbl_t1(id int, val1 text, val2 text, val3 text);"
psql -p $PUB_PORT postgres -c "CREATE PUBLICATION mypub FOR TABLE tbl_pub;"

# Setup the subscriber database
psql -p $SUB_PORT postgres -c "CREATE TABLE tbl_pub(id int, val1 text, val2 text, val3 text);"
psql -p $SUB_PORT postgres -c "CREATE TABLE tbl_t1(id int, val1 text, val2 text, val3 text);"
psql -p $SUB_PORT postgres -c "CREATE SUBSCRIPTION mysub CONNECTION 'host=127.0.0.1 port=$PUB_PORT dbname=postgres' PUBLICATION mypub WITH ( streaming = off);"

# Wait for replication to sync
sleep 5  

# Measure initial disk usage
echo "Initial disk usage in replication slot directory:"
du -sh "$PG_SLOT_DIR"

# Perform a large insert into an unpublished table
psql -p $PUB_PORT postgres -c "
    BEGIN;
    INSERT INTO tbl_t1 
    SELECT i, repeat('xyzzy', i % 10), repeat('abcba', i % 10), repeat('dfds', i % 10) 
    FROM generate_series(1, 1000000) i;
    COMMIT;"

# Wait for logical decoding to process

# Measure final disk usage
echo "Final disk usage in replication slot directory:"
du -sh "$PG_SLOT_DIR"

# Cleanup
# Setup the publisher database
psql -p $PUB_PORT postgres -c "DROP TABLE tbl_pub;"
psql -p $PUB_PORT postgres -c "DROP TABLE tbl_t1;"
psql -p $PUB_PORT postgres -c "DROP PUBLICATION mypub;"

# Setup the subscriber database
psql -p $SUB_PORT postgres -c "DROP TABLE tbl_pub;"
psql -p $SUB_PORT postgres -c "DROP TABLE tbl_t1;"
psql -p $SUB_PORT postgres -c "DROP SUBSCRIPTION mysub;"

echo "Test completed."
