
# Paths
PGDIR=`pwd`
INSTDIR=$PGDIR/tmp_install
M=$PGDIR/PGDATA
M1=$PGDIR/PGDATA_REPL
U=`whoami`
export LD_LIBRARY_PATH=$INSTDIR/lib:$LD_LIBRARY_PATH
export PATH=$INSTDIR/bin:$PATH

# Clear data of previous launch
pkill -U $U -9 -e postgres
rm -rf $M || true
mkdir $M
rm -rf $M1 || true
mkdir $M1
rm -rf logfile.log || true
rm -rf logfile_repl.log || true

make
make install

initdb -D $M
initdb -D $M1

# Additional preferences
echo "wal_level = 'logical'" >> $M/postgresql.conf
echo "wal_level = 'logical'" >> $M1/postgresql.conf

pg_ctl -w -D $M -l logfile.log start
pg_ctl -o "-p 5433" -w -D $M1 -l logfile_repl.log start
createdb $U
createdb -p 5433 $U

init_sql="CREATE DOMAIN things AS INT; CREATE TABLE thethings (key things PRIMARY KEY);"
psql -c "$init_sql"
psql -p 5433 -c "$init_sql"

psql -c "CREATE PUBLICATION mpub FOR TABLE thethings"
psql -p 5433 -c "CREATE SUBSCRIPTION mysub CONNECTION 'port=5432 dbname=$U' PUBLICATION mpub;"

psql -c "INSERT INTO thethings (key) VALUES (11);"
sleep 10 # Wait for the replication sync of INSERT command

psql -c "ALTER DOMAIN things ADD CONSTRAINT meow CHECK (VALUE < 11) NOT VALID;"
psql -p 5433 -c "ALTER DOMAIN things ADD CONSTRAINT meow CHECK (VALUE < 11) NOT VALID;"
psql -c "UPDATE thethings SET key = key - 1;"
sleep 10 # Wait for the replication sync of UPDATE command

psql -p 5433 -c "SELECT * FROM thethings;" # we can't found new version of tuple

# See problems at the postgres logs of master and slave nodes

