#!/bin/bash
#include <genscript.warning>

# Enable a procedural language for PostgreSQL in one or more
# existing databases

enable_database() {
	# the database name is the first parameter to this function
	x="select count(*) from pg_language where lanname='$lang'"
	RES=$(psql -d "$1" -qtc "$x" 2>&1) || {
		echo "Cannot connect to $1"
		exit 2
	}
	if [ "$RES" -eq 0 ]
	then
		if ! /usr/lib/postgresql/bin/createlang $lang "$1"
		then
			echo "Failed to add $lang to $1"
			exit 2
		fi
		echo "$lang added to $1"
	else
		echo "$lang is already enabled in $1"
	fi
}

# Execution starts here

if ! pidof /usr/lib/postgresql/bin/postmaster > /dev/null
then
	echo The postgresql package must be installed and the postmaster started before
	echo this script can be run.
	exit 1
fi

# Need unrestricted access
ACCESS=`grep '^[[:space:]]*local[[:space:]]\+all[[:space:]]\+postgres[[:space:]]' /etc/postgresql/pg_hba.conf | awk '{print $4}'`
if [ "$ACCESS" != trust -a "$ACCESS" != ident -a ! -f ~postgres/.pgpass ]
then
	echo Sorry! I need unrestricted access in /etc/postgresql/pg_hba.conf to update
	echo the databases.  Edit the file to give postgres local access to all databases
	echo with "trust" or "ident sameuser" authentication, or create a .pgpass file
	echo "in ~postgres (see manual)."
	exit
fi

if ! [ -r /etc/postgresql/postgresql.env ] 
then
	echo "/etc/postgresql/postgresql.env (from postgresql-client)
is missing.  Reinstall postgresql-client."
	exit 1
fi

. /etc/postgresql/postgresql.env
installed=`cat ${PGDATA}/PG_VERSION`
current=%PG_VERSION%

if [ -n "$installed" -a "$installed" != $current ]
then
	echo "I cannot install the $lang language while the database version differs from the"
	echo "current version. Run enable_lang as the postgres user, after using postgresql-dump"
	echo "(from the postgresql package) to dump and reload the database."
	echo
	echo -n "Press <return> to continue: "
	read x
	exit 0
fi

# read command line
while [ -n "$1" ]
do
	if [ -z "$lang" ]
	then
		lang=$1
	else
		dblist="$dblist
$1"
	fi
	shift
done
	
if [ -z "$lang" -o -z "$dblist" ]
then
	echo "Syntax: $0 language --all | database ..."
	exit 1
fi

if [ ! -x /usr/lib/postgresql/bin/createlang ]
then
	echo "No executable createlang"
	exit 2
fi

if [ $dblist = "--all" ]
then
	DB=$(psql -A -d template1 -t -c "select datname from pg_database where datallowconn order by datname") || {
		echo Cannot select databases
		exit 2
	}
	IFS='
'
	for database in $DB
	do
		enable_database "$database"
	done
else
	for database in $dblist
	do
		enable_database "$database"
		shift
	done
fi
