#!/bin/sh
#
# pg_upgrade: update a database without needing a full dump/reload cycle
# CAUTION: read the manual page before trying to use this!

trap "rm -f /tmp/$$" 0 1 2 3 15

if [ "$#" -eq 0 ]
then	echo "Usage:  $0 [-f inputfile] old_data_dir" 1>&2
	exit 1
fi

if [ "X$1" = "X-f" ]
then	INPUT="$2"
	shift 2
	if [ ! -f "$INPUT" ]
	then	echo "$INPUT does not exist" 1>&2
		exit 1
	fi
else	INPUT=""
fi

if [ "$#" -ne 1 ]
then	echo "Usage:  $0 [-f inputfile] old_data_dir" 1>&2
	exit 1
fi

OLDDIR="$1"

# check things

if [ ! -f "./lib/global1.bki.source" ]
then	echo "$0 must be run from the top of the postgres directory tree." 1>&2
	exit 1
fi

if [ ! -d "./$OLDDIR" ]
then	echo "You must rename your old /data directory to /$OLDDIR and run initdb." 1>&2
	exit 1
fi

if [ ! -d "./$OLDDIR/base/template1" ]
then	echo "There is not database template1 in ./$OLDDIR/base." 1>&2
	exit 1
fi

if [ ! -d "./data" ]
then	echo "You must run initdb to create the template1 database." 1>&2
	exit 1
fi

if [ ! -d "./data/base/template1" ]
then	echo "$0 must be run as the postgres superuser." 1>&2
	exit 1
fi

# do I need to create a database?

# remove any COPY statements
# we don't even need pgdump_oid because we are moving pg_variable
# then shouldn't be in there anyway

cat $INPUT | awk '	{
				if (toupper($1) == "COPY" && $2 != "pg_shadow")
					while (getline $0 > 0 && $0 != "\\.")
						;
				else	print $0;
			}' >/tmp/$$
 
#create empty tables/indexes

psql "template1" <"/tmp/$$"

if [ $? -ne 0 ]
then	echo "psql failed to execute $INPUT script." 1>&2
	exit 1
fi

for DIR in data/base/*
do
	BASEDIR="`basename $DIR`"
	if [ -d "$DIR" -a \
	     -d "$OLDDIR/base/$BASEDIR" -a \( "$BASEDIR" != "template1" \) ]
	then	for FILE in $OLDDIR/base/$BASEDIR/*
		do
			BASEFILE="`basename $FILE`"
			if [ `expr "$BASEFILE" : "pg_"` -ne 3 -a \
				"$BASEFILE" != "PG_VERSION" ]
			then	mv $FILE $DIR
			fi
		done
	fi
done

mv $OLDDIR/pg_log data
mv $OLDDIR/pg_variable data

echo "You may remove the $OLDDIR directory with 'rm -r $OLDDIR'."
