#!/bin/bash
# this script will change it's current working directory to utils

DB=postgis_uninstall

PGPATH=../postgis/
RTPATH=../raster/rt_pg/

PGFILE=uninstall_postgis.sql
RTFILE=uninstall_rtpostgis.sql

if [ "raster" == "$1" ]; then
	OUTFILE=$RTFILE
else
	OUTFILE=$PGFILE
fi
INFILE=$OUTFILE.in.$RANDOM
RAND1=$RANDOM
RAND2=$RANDOM

RTN=0

cleanup () {
	rm -f $INFILE $OUTFILE.$RAND1 $OUTFILE.$RAND2
}

# get reference uninstall of postgis.sql only
if [ "$1" == "raster" ]; then
	$0
fi

SOURCE="${BASH_SOURCE[0]}"
while [ -h "$SOURCE" ] ; do SOURCE="$(readlink "$SOURCE")"; done
DIR="$( cd -P "$( dirname "$SOURCE" )" && pwd )"

# use utils as our working directory
cd $DIR

# create database
createdb $DB

# load postgis.sql
psql -q -d $DB -f ${PGPATH}postgis.sql

# raster requested, load rtpostgis.sql
if [ "$1" == "raster" ]; then
	psql -q -d $DB -f ${RTPATH}rtpostgis.sql
fi

# dump database loaded with postgis.sql and rtpostgis.sql and strip for only one-line DROP and SET statements
pg_dump --format=p --clean --schema-only --no-owner --no-acl --no-tablespaces $DB | grep -E "^(DROP|SET).*;$" | grep -v -E "^DROP (SCHEMA|PROCEDURAL) .*;$" > $INFILE

# drop database
dropdb $DB

# first search_path is parsed
schema=`grep -m 1 "SET search_path = " < $INFILE | sed -e 's/SET search_path = //' -e 's/\(,\|;\)//g' -e 's/ /\n/'`

# sed arguments
sedarg="\-e 's/^DROP \(TABLE\|VIEW\|CAST\|OPERATOR CLASS\|OPERATOR\|AGGREGATE\|FUNCTION\|TYPE\)/& IF EXISTS/' "
for x in $schema; do
	sedarg="\-e 's/${x}.//g' "${sedarg}
done

# remove SET statements, remove schema names from DROP statements and add IF EXISTS for DROP statements
grep -v -E "^SET" < $INFILE | eval "sed ${sedarg}" > $OUTFILE.$RAND1
RTN=$?

if [ "$RTN" != "0" ]; then
	cleanup
	exit $RTN
fi

kw=""
OIFS=$IFS
IFS=$'\n'
echo -n '' > $OUTFILE.$RAND2
for x in `cat $OUTFILE.$RAND1`; do
	y=`echo "$x" | grep "CASCADE;\$"`
	# CASCADE found, get keyword
	if [ "x$y" != "x" ]; then
		kw=`echo "$x" | sed -e 's/^DROP TYPE IF EXISTS //' -e 's/ CASCADE;//'`
		echo "$x" >> $OUTFILE.$RAND2
		continue
	fi

	# no keyword, continue
	if [ "x$kw" == "x" ]; then
		echo "$x" >> $OUTFILE.$RAND2
		continue
	fi

	y=`echo "$x" | grep "($kw)"`
	if [ "x$y" == "x" ]; then
		echo "$x" >> $OUTFILE.$RAND2
		continue
	fi
done
IFS=$OIFS

# if raster, separate raster from postgis items
if [ "raster" == "$1" ]; then
	OIFS=$IFS
	IFS=$'\n'

	echo -n '' > ${RTPATH}$OUTFILE

	# see if line found in uninstall_postgis.sql
	for x in `cat $OUTFILE.$RAND2`; do
		y=`echo $x | sed -e 's/\(\[\|\]\)/\\\&/g'`
		y=`grep "^${y}$" < ${PGPATH}$PGFILE`

		# not postgis item
		if [ "x$y" == "x" ]; then
			echo $x >> ${RTPATH}${OUTFILE}
		fi
	done

	IFS=$OIFS
else
	mv $OUTFILE.$RAND2 ${PGPATH}${OUTFILE}
fi

# cleanup
cleanup

# return error
exit $RTN
