PGUSER="${PGUSER:-postgres}"
PGDATABASE="${PGDATABASE:-template_gis}"
PGPATH="${PGPATH:-/usr/share/postgresql/contrib}"
ROOT="/"

displayGood(){
    echo -ne '\033[1m\E[49;33m' \*  '\033[1m\033[0m'
    echo "$1"
}

displayBad(){
   echo -ne '\033[1m\E[49;31m' \*  '\033[1m\033[0m'
   echo "$1"
}

die(){
    displayBad "$1"
    exit -1
}

trap "displayGood 'Operation canceled, good bye';exit 0" 2

is_template=false
if [ "${PGDATABASE:0:8}" == "template" ];then
	is_template=true
	mytype="template database"
else
	mytype="database"
fi

displayGood "Using the user ${PGUSER} and the ${PGDATABASE} ${mytype}."
displayGood "Please do 'export PGUSER=...' to use another user."
displayGood "Please do 'export PGDATABASE=...' to set another template/database"
displayGood "name (templates name have to be prefixed with 'template')."

logfile=$(mktemp "${ROOT}tmp/error.log.XXXXXX")

safe_exit(){
	displayBad "Removing created ${mydb} ${mytype}"
	dropdb -q || (displayBad "${1}"
		die "Removing old db failed, you must do it manually")
	displayBad "Please see ${logfile} for more information."
	die "${1}"
}

# if there is not a table or a template existing with the same name, create.
PGDBS="$(psql -ql 2> ${logfile})"
if [ "$?" == 2 ];then
   die "Unable to access databases server using the ${PGUSER} user"
fi

PGDBS="$(psql template1 -U postgres -Atc \
    "select 1 from pg_tables where tablename='${PGDATABASE}';")"
if [ "${PGDBS}" != "1" ]; then
	displayGood
	displayGood "Please hit ENTER if you want to create the ${PGDATABASE}"
	displayGood "${mytype} as "${PGUSER}" user, or Control-C to abort now..."
	read
	displayGood "Creating the ${mytype} ${PGDATABASE}."
	createdb -q -O ${PGUSER} ||\
		die "Unable to create the ${mydb} ${mytype} as ${myuser}"
	createlang plpgsql
	if [ "$?" == 2 ]; then
			safe_exit "${myuser} not allowed to createlang plpgsql ${mydb}."
	fi
	displayGood "Loading PostGIS files into ${PGDATABASE}."
	(psql -q -f "${PGPATH}"/lwpostgis.sql && 
        psql -q -f "${PGPATH}"/spatial_ref_sys.sql) 2>\
			"${logfile}"
	if [ "$(grep -c ERROR "${logfile}")" \> 0 ]; then
			safe_exit "Unable to load the sql files."
	fi
	if ${is_template}; then
		displayGood "Configure ${PGDATABASE} as a ${mytype}"
		PSEUDO_TABLES="'pg_xactlock', 'sql_features',
			'sql_implementation_info', 'sql_languages', 
			'sql_packages', 'sql_sizing', 'sql_sizing_profiles'"
		TABLES=$(psql -At -c \
			"select tablename from pg_tables 
			where tablename not in (${PSEUDO_TABLES});")
		for table in $TABLES ; do
			psql -q -c "alter table ${table} owner to ${PGUSER};"
		done
		myid=$(psql -q -d template1 -At \
			-c "select usesysid from pg_user where usename='${PGUSER}';")
		psql -q  -c \
			"UPDATE pg_class SET relowner=${myid} WHERE relkind = 'S';
			UPDATE pg_database SET datistemplate = TRUE
			WHERE datname = '${PGDATABASE}';
			UPDATE pg_database SET datallowconn = FALSE
			WHERE datname = '${PGDATABASE}';
			VACUUM FULL;
			VACUUM FREEZE;" || die "Unable to create ${mydb}"
	fi
else
	displayGood
	displayGood "Please hit ENTER if you want to upgrade the ${mydb}"
	displayGood "${mytype} as ${myuser} user, or Control-C to abort now..."
	read
	if [ -e "${ROOT}"usr/share/postgresql/contrib/load_before_upgrade.sql ];
	then
		displayGood "Updating the dynamic library references"
		psql -q -f \
			"${ROOT}"usr/share/postgresql/contrib/load_before_upgrade.sql\
				2> "${logfile}"
		if [ "$(grep -c ERROR "${logfile}")" \> 0 ]; then
			safe_exit "Unable to update references."
		fi
	fi
	if [ -e "${ROOT}"usr/share/postgresql/contrib/lwpostgis_upgrade.sql ];
	then
		displayGood "Running soft upgrade"
		psql -q -f \
			"${ROOT}"usr/share/postgresql/contrib/lwpostgis_upgrade.sql 2>\
				"${logfile}"
		if [ "$(grep -c ERROR "${logfile}")" \> 0 ]; then
			safe_exit "Unable to run soft upgrade."
		fi
	fi
fi

if ${is_template}; then
    displayGood "You can now create a spatial database using :"
	displayGood "'createdb -T ${PGDATABASE} test'"
fi
