#!/bin/sh
# $Id$

#set -x
. ./install_var.sh


if [ "${UID}" = "0" ]; then
	echo "Error: install_postgres.sh should run as postgres."
	exit 1
fi

USEREXIST=$(psql template1 -At -c "select usesysid from pg_shadow where usename='${PGUSER}'")
if [ -z "${USEREXIST}" ]; then
	psql template1 -c "CREATE USER ${PGUSER} WITH NOCREATEDB NOCREATEUSER ENCRYPTED PASSWORD '`head /dev/urandom | md5sum | cut -c1-16`'"
	if [ $? -ne 0 ]; then
		echo "Error: could not create user in postgresql"
		exit $?
	fi
else
	echo "User allready created: ${PGUSER}"
fi

DBEXIST=$(psql -l | grep ${PGDATABASE})
if [ -z "${DBEXIST}" ]; then
	createdb -E utf8 -O ${PGUSER} ${PGDATABASE}
	DBEXIST=$(psql -l | grep ${PGDATABASE})
	if [ -z "${DBEXIST}" ]; then
		echo "Failed to create database: ${PGDATABASE}"
		exit 1
	fi
else
	echo "Database allready created: ${PGDATABASE}"
fi

INSTALLEDPLPG=$(psql -At -c "select probin from pg_proc where proname='plpgsql_call_handler'" ${PGDATABASE})

if [ -z "${INSTALLEDPLPG}" ]; then
	# Try to guess where plpgsql.so is located.
	# 'psql' could be found in: /usr/local/pgsql/bin/psql
	# and then remove '/bin/psql'
	LOC="`which psql`"
	LOC="${LOC%/*}"
	LOC="${LOC%/*}/lib/plpgsql.so"

	LOCATIONS="$1 ${PLPGSQL} ${LOC} /usr/local/pgsql/lib/plpgsql.so /usr/local/lib/postgresql/plpgsql.so /usr/lib/postgresql/plpgsql.so"
	SO=""
	for LOC in ${LOCATIONS} $1; do
		if [ -e ${LOC} ]; then
			SO="${LOC}"
			echo "'plpgsql.so' found in: ${SO}"
			break
		fi
	done

	if [ -z "${SO}" ]; then
		echo "'plpgsql.so' was not found in:"
		for LOC in ${LOCATIONS}; do
			echo " * ${LOC}"
		done
		echo "Specify the location in 'install_var.sh'."
		echo "Installation aborted."
		exit 1
	fi

	psql ${PGDATABASE} -At -c "create function plpgsql_call_handler() returns language_handler as '${SO}' language 'C'"
	psql ${PGDATABASE} -At -c "create trusted procedural language 'PLpgSQL' handler plpgsql_call_handler lancompiler 'PL/pgSQL'"
else
	echo "'plpgsql.so' is already installed: ${INSTALLEDPLPG}"
fi

