#!/bin/bash

##
## Description
##
## This test creates a very small file system for pg_wal and
## causes disk shortage while inserting a large WAL record.
## After crashing, if .ready of segment 1 is not created in archive_status directory, 
## the patch works well.
##

##
## parameter of environment
##
basedir=$HOME
testname=bugfix_early_archiving
installdir=$basedir/dev/postgresql
datadir=$basedir/var
export PATH=$installdir/bin:$PATH
export LD_LIBRARY_PATH=$installdir/lib:$LD_LIBRARY_PATH
export PGDATA=$datadir/$testname

##
## setup
##
sudo ls >/dev/null
if [ $? != 0 ]; then
	echo "sudoer privileges is needed"
	exit 1
fi

workdir=$basedir/var/${testname}_work
mkdir -p $workdir
mntpt=$basedir/var/${testname}_mnt
mkdir -p $mntpt

imgfile=$workdir/img
dd if=/dev/zero of=$imgfile bs=1M count=30
mkfs.xfs $imgfile
sudo umount $mntpt
sudo mount -t xfs -o loop $imgfile $mntpt
sudo chmod 777 $mntpt

rm -rf $PGDATA
initdb

mkdir -p $mntpt/pg_wal
mv $PGDATA/pg_wal/* $mntpt/pg_wal/
rm -rf $PGDATA/pg_wal/
ln -s $mntpt/pg_wal $PGDATA

pg_ctl start
psql -d template1 -c "alter system set archive_mode to always"
psql -d template1 -c "alter system set archive_command to 'test ! -f "$workdir"/%f && cp %p "$workdir"/%f'"
pg_ctl stop

##
## running
##
## This inserting sequence will fail because of disk shortage.
## If .ready of segment 1 is not created in archive_status directory, 
## the patch works well.
##
pg_ctl start
psql -d template1 -c "create table t(c bytea);"
psql -d template1 -c "insert into t select pg_read_binary_file('"$imgfile"');"
psql -d template1 -c "insert into t select pg_read_binary_file('"$imgfile"');"
psql -d template1 -c "insert into t select pg_read_binary_file('"$imgfile"');"
psql -d template1 -c "insert into t select pg_read_binary_file('"$imgfile"');"
pg_ctl stop

