#!/bin/sh
## WARNING TO MAINTAINERS - DO NOT EDIT this file in debian/.  It will be
## overwritten by debian/rules.  Edit the .in template instead.

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

enable_database() {
	if ! psql -d $1 -qtc "select count(*) from pg_language where lanname='plpgsql'" >$TMPFIL2 2>&1
	then
		echo "Cannot connect to $1"
		exit 2
	fi
	if [ `cat $TMPFIL2` -eq 0 ]
	then
		if ! psql -d $1 <$sqlfile
		then
			echo "Failed to add PL to $1"
			exit 2
		fi
		echo "PL added to $1"
	else
		echo "PL is already enabled in $1"
	fi

}

# Execution starts here

TMPFILE=`mktemp /tmp/enable_pgpl.XXXXXX`
TMPFIL2=`mktemp /tmp/enable_pgpl.XXXXXX`
trap "rm $TMPFILE $TMPFIL2" EXIT

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

if [ -n "$installed" -a "$installed" != $current ]
then
	echo "I cannot install the PL language while the database version differs from the"
	echo "current version. Run enable_pgpl 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

if [ -z "$1" ]
then
	echo "Syntax: $0 --all | database ..."
	exit 1
fi

sqlfile=${PGLIB}/mklang_pl.sql
if [ ! -f $sqlfile ]
then
	echo "Cannot find mklang_pl.sql"
	exit 2
fi

if [ $1 = "--all" ]
then
	if ! psql -t -c "select datname from pg_database order by datname" >$TMPFILE
	then
		echo Cannot select databases
		exit 2
	fi
	for db in `cat $TMPFILE`
	do
		enable_database $db
	done
else
	while [ -n "$1" ]
	do
		db=$1
		enable_database $db
		shift
	done
fi
