#!/bin/sh
# Utilities needed
# 1. sh
# 3. sed 
if [ -z "$PGDATA" ]; then
	echo "PGDATA environment variable is not set. Stop." 1>&2
	exit 2
fi
if [ -e "$PGDATA/recovery.conf" ]; then
	echo "recovery.conf exists in PGDATA. No upgrade script could be run." 1>&2
	exit 0
fi
PGBIN="`echo $0|sed 's![^/\\]*$!!'`"
if [ "$1" = "--check" ]; then
   check=1
else
   check=
fi
echo "$PGBIN"

case "$PGBIN" in
*/bin/|*\\bin\\)
	PGSHARE="`echo $PGBIN|sed 's!bin.$!share!'`"
	;;
*) PGBIN=""
	PGSHARE=""
;;
esac

for dir in "$PGSHARE" /usr/pgsql-9.6/share /usr/share/postgresql/9.6 /usr/pgsql/9.6/share /usr/share/pgsql /usr/share/postgrespro96  ; do
	if [ -d "$dir/pgpro-upgrade" ]; then
		DIR="$dir/pgpro-upgrade"
		break
	fi
done
if [ -z "$DIR" ]; then
	echo "Cannot find feature scripts" 1>&2
	exit 1
fi
BASELIST=`echo "select datname from pg_database;"|
	"${PGBIN}postgres" --single template0 |
	sed -n 's/^.*1: datname = "\([^"]*\)".*$/\1/p'`

if [ -z "$BASELIST" ]; then
	echo "Databases for upgrade not found" 1>&2
	exit 1
fi

[ -z "$check" ]&& echo "Upgrading databases $BASELIST"

#Search for upgrade scripts
need_upgrade=0
for i in "$DIR"/*.test; do
	found=`< "$i"  "${PGBIN}postgres" --single template0 | 
		sed -n 's/^[	 ]*1: [^ ]* = "\([ft]\)"[ 	].*$/\1/p'` 
	if [ "$found" = "f" ]; then	
		if [ -z "$check" ]; then
			create="`echo "$i" |sed 's/\.test$/.sql/'`"
			for base in $BASELIST; do
				echo "Executing $create in $base"
				< "$create"  "${PGBIN}postgres" --single "$base" >/dev/null

			done
		else 
			need_upgrade=1
		fi
	fi
done
if [ -n "$check" ]; then
	if [ $need_upgrade -eq 0 ]; then
		echo "All Postgres Pro specific updates are applied" 1>&2
	else
		echo "Database needs upgrade"
	fi
	exit $need_upgrade
fi
