#!/bin/sh

INSTALLED=$(psql -At -c "select probin from pg_proc where proname='plpgsql_call_handler'")

# 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 ${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
	echo "Usage:"
	echo "  $0 <path-to-plpgsql.so'>"
	echo
	echo "Installation aborted."
	exit
fi

if [ -z "${INSTALLED}" ]; then
	echo "create function plpgsql_call_handler() returns language_handler as '${SO}' language 'C'" | psql
	echo "create trusted procedural language 'PLpgSQL' handler plpgsql_call_handler lancompiler 'PL/pgSQL'" | psql
else
	echo "'plpgsql.so' is already installed:"
	ls -l ${INSTALLED}
fi

