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

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


git checkout REL9_6_STABLE
make distclean -s
./configure --prefix=$WORKDIR/postgresql_bin_9_6
make -j4 -s
make install -j4 -s

rm -rf $WORKDIR/postgresql_data_9_6
mkdir $WORKDIR/postgresql_data_9_6
$WORKDIR/postgresql_bin_9_6/bin/initdb -D $WORKDIR/postgresql_data_9_6

$WORKDIR/postgresql_bin_9_6/bin/pg_ctl -D $WORKDIR/postgresql_data_9_6 start -w
$WORKDIR/postgresql_bin_9_6/bin/psql -c "select version();" postgres
$WORKDIR/postgresql_bin_9_6/bin/psql -c "CREATE ROLE backup WITH LOGIN;" postgres
$WORKDIR/postgresql_bin_9_6/bin/psql -c "GRANT USAGE ON SCHEMA pg_catalog TO backup;" postgres
$WORKDIR/postgresql_bin_9_6/bin/psql -c "GRANT EXECUTE ON FUNCTION pg_stop_backup() TO backup;" postgres
$WORKDIR/postgresql_bin_9_6/bin/psql -c "GRANT EXECUTE ON FUNCTION pg_stop_backup(boolean) TO backup;" postgres

$WORKDIR/postgresql_bin_9_6/bin/pg_ctl -D $WORKDIR/postgresql_data_9_6 stop -w

git checkout REL_10_STABLE
make distclean -s
./configure --prefix=$WORKDIR/postgresql_bin_10
make -j4 -s
make install -j4 -s

rm -rf $WORKDIR/postgresql_data_10
mkdir $WORKDIR/postgresql_data_10
$WORKDIR/postgresql_bin_10/bin/initdb -D $WORKDIR/postgresql_data_10

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

# Fails at "Restoring database schemas in the new cluster"
$WORKDIR/postgresql_bin_10/bin/pg_upgrade \
-k --old-bindir=$WORKDIR/postgresql_bin_9_6/bin \
 --new-bindir=$WORKDIR/postgresql_bin_10/bin \
  --old-datadir=$WORKDIR/postgresql_data_9_6 \
   --new-datadir=$WORKDIR/postgresql_data_10