#!/bin/sh

set -e

echo "*** This script will mess the /tmp/pg_bug_backup_tblspace folder and leave you two pg running on ports 5550 and 5551"
echo "*** so happy cleaning after me !"

PG1=/usr/lib/postgresql/9.5/bin
PG2=/usr/lib/postgresql/9.6/bin
PORT1=5550
PORT2=5551

cd /tmp
mkdir pg_bug_backup_tblspace
cd pg_bug_backup_tblspace

mkdir source_server
cd source_server
mkdir datas
mkdir tblspc
cd datas
$PG1/initdb pg1
$PG1/postgres -k /tmp --port=$PORT1 -D pg1 &
echo "local replication all  trust" >> pg1/pg_hba.conf
echo "wal_level = hot_standby" >> pg1/postgresql.conf
echo "max_wal_senders = 10" >> pg1/postgresql.conf

sleep 3         # HACK
$PG1/psql -h /tmp --port $PORT1 -c "CREATE TABLESPACE demo LOCATION '/tmp/pg_bug_backup_tblspace/source_server/tblspc';" postgres
$PG2/initdb pg2
$PG2/postgres -k /tmp --port=$PORT2 -D pg2 &
echo "local replication all  trust" >> pg2/pg_hba.conf
echo "wal_level = hot_standby" >> pg2/postgresql.conf
echo "max_wal_senders = 10" >> pg2/postgresql.conf
sleep 3         # HACK
$PG2/psql -h /tmp --port $PORT2 -c "CREATE TABLESPACE demo LOCATION '/tmp/pg_bug_backup_tblspace/source_server/tblspc';" postgres
cd ../..

echo "************************ STARTED THE ORIGIN SERVERS ************************"
echo "************************ PREPARING BACKUPS ************************"
mkdir dest_server
cd dest_server
mkdir datas
mkdir tblspc
cd datas
echo "************************ FIRST BASEBACKUP ************************"
$PG1/pg_basebackup -h /tmp -p $PORT1 -D pg1 --tablespace-mapping=/tmp/pg_bug_backup_tblspace/source_server/tblspc=/tmp/pg_bug_backup_tblspace/dest_server/tblspc
echo "************************ SECOND BASEBACKUP ************************"
echo "Expecting it to fail with 'directory \"/tmp/pg_bug_backup_tblspace/dest_server/tblspc\" exists but is not empty'"
$PG2/pg_basebackup -h /tmp -p $PORT2 -D pg2 --tablespace-mapping=/tmp/pg_bug_backup_tblspace/source_server/tblspc=/tmp/pg_bug_backup_tblspace/dest_server/tblspc

