#!/bin/bash
set -euxo pipefail 

PATH=/home/heikki/pgsql.master/bin:$PATH

TABLESPACE_PATH='/mnt/otherdisk/heikki'

pkill -9 postgres || true
rm -rf /home/heikki/fsynctest-data

rm -rf $TABLESPACE_PATH/testspc
mkdir $TABLESPACE_PATH/testspc

sync

initdb -D /home/heikki/fsynctest-data

pg_ctl -D /home/heikki/fsynctest-data start -w

psql postgres -c "CREATE TABLESPACE fsynctestvol LOCATION '$TABLESPACE_PATH/testspc'"

psql postgres -c "CHECKPOINT"

psql postgres -c "CREATE UNLOGGED TABLE unlogged_tbl (t text)"
psql postgres -c "INSERT INTO unlogged_tbl SELECT g FROM generate_series(1, 10000000) g"


psql postgres -c "ALTER TABLE unlogged_tbl SET TABLESPACE fsynctestvol" &
alter_table_pid=$!

sleep 1
psql postgres -c "CHECKPOINT"

wait $alter_table_pid

# clean shutdown
pg_ctl -D /home/heikki/fsynctest-data stop -w

echo "KILL VM NOW"

