# Run this script in a directory that contains postgres git repository with
# old_version and new_version branches
#
# Set WORKDIR as a root path for binaries and pgdata directories

 WORKDIR="/tmp/workdir"
 export WORKDIR="/tmp/workdir"

# path to the directory with a patchset:
#    pg_upgrade_ACL_check_v6.patch
#    test_rename_catalog_objects.patch
#    test_add_acl_to_catalog_objects.sql
PATCHDIR="/home/anastasia/original_repo/cf_2215"
# branch name - upgrade from
 OLD_VERSION="REL_12_STABLE"
 # branch name - upgrade to
 NEW_VERSION="master"

git checkout $OLD_VERSION
make distclean -s
./configure --prefix=$WORKDIR/postgresql_bin_test_old
make -j4 -s
make install -j4 -s

rm -rf $WORKDIR/postgresql_data_test_old
mkdir $WORKDIR/postgresql_data_test_old
$WORKDIR/postgresql_bin_test_old/bin/initdb -D $WORKDIR/postgresql_data_test_old

$WORKDIR/postgresql_bin_test_old/bin/pg_ctl -D $WORKDIR/postgresql_data_test_old start -w
$WORKDIR/postgresql_bin_test_old/bin/psql -c "select version();" postgres
$WORKDIR/postgresql_bin_test_old/bin/psql -f $PATCHDIR/test_add_acl_to_catalog_objects.sql postgres


$WORKDIR/postgresql_bin_test_old/bin/pg_ctl -D $WORKDIR/postgresql_data_test_old stop -w

#git clean -f
git checkout $NEW_VERSION

patch -p1 < $PATCHDIR/pg_upgrade_ACL_check_v6.patch
# specific patch that renames system objects to test new feature
patch -p1 < $PATCHDIR/test_rename_catalog_objects.patch

   make distclean -s
   ./configure --prefix=$WORKDIR/postgresql_bin_test_new --enable-cassert --enable-debug --enable-depend CFLAGS="-O0 -g2"
   make -j4 -s
 make install -j4 -s

rm -rf $WORKDIR/postgresql_data_test_new
mkdir $WORKDIR/postgresql_data_test_new
$WORKDIR/postgresql_bin_test_new/bin/initdb -D $WORKDIR/postgresql_data_test_new

$WORKDIR/postgresql_bin_test_new/bin/pg_ctl -D $WORKDIR/postgresql_data_test_new start -w
$WORKDIR/postgresql_bin_test_new/bin/psql -c "select version();" postgres
$WORKDIR/postgresql_bin_test_new/bin/pg_ctl -D $WORKDIR/postgresql_data_test_new stop -w

# Fails at "Checking for system objects to grant or revoke privileges" with patch
$WORKDIR/postgresql_bin_test_new/bin/pg_upgrade \
-k --old-bindir=$WORKDIR/postgresql_bin_test_old/bin \
 --new-bindir=$WORKDIR/postgresql_bin_test_new/bin \
  --old-datadir=$WORKDIR/postgresql_data_test_old \
   --new-datadir=$WORKDIR/postgresql_data_test_new --check

cat ./revoke_objects.sql

$WORKDIR/postgresql_bin_test_old/bin/pg_ctl -D $WORKDIR/postgresql_data_test_old start -w
$WORKDIR/postgresql_bin_test_old/bin/psql postgres -f ./revoke_objects.sql
$WORKDIR/postgresql_bin_test_old/bin/pg_ctl -D $WORKDIR/postgresql_data_test_old stop -w

# Must succeed
$WORKDIR/postgresql_bin_test_new/bin/pg_upgrade \
-k --old-bindir=$WORKDIR/postgresql_bin_test_old/bin \
 --new-bindir=$WORKDIR/postgresql_bin_test_new/bin \
  --old-datadir=$WORKDIR/postgresql_data_test_old \
   --new-datadir=$WORKDIR/postgresql_data_test_new --check