# /bin/bash


# --------------------------------------------------------------
#
# Installs 'plpgsql' as a trusted language in a given database.
#
# Author:  Zlatko Michailov
# Created: 18-Dec-2003
# Updated: 17-Jan-2004
#
# --------------------------------------------------------------

if [[ "$1" != "--help" ]]
then
	# Check access to languages in database
	sql="select count( lanname ) from pg_language;"
	res=`./psql1 "$@" -c "$sql"`
	echo ""
	ext="1"
fi

if [[ "$res" != "" ]]
then
	# Check status of 'plpgsql'
	sql="select lanpltrusted from pg_language where lanname = 'plpgsql';"
	res=`./psql1 "$@" -c "$sql"`
	ans="n"

	case "$res" in
		# installed, trusted
		"t" | "T" )
			echo "OK: 'plpgsql' is installed as trusted"
			ext="0"
			;;

		# not installed
		"(0" )
			echo "'plpgsql' is not installed."
			read -p "Do you want to install it (Y/N)?" -n 1 ans
			echo ""

			if [[ "$ans" == "y" || "$ans" == "Y" ]]
			then
				createlang "$@" plpgsql
			fi
			;;

		# installed, not trusted
		"f" | "F" )
			echo "'plpgsql' is installed but is not trusted."
			echo "Non-admin users are not able to execute functions and triggers."
			read -p "Do you want to trust 'plpgsql' for non-admin users (Y/N)?" -n 1 ans
			echo ""

			if [[ "$ans" == "y" || "$ans" == "Y" ]]
			then
				sql="update pg_language set lanpltrusted = 't' where lanname = 'plpgsql';"
				psql "$@" -c "$sql" > nul
			fi
			;;
	esac

	# Upgrade was to be done. Check new ststus.
	if [[ "$ans" == "y" || "$ans" == "Y" ]]
	then
		sql="select lanpltrusted from pg_language where lanname = 'plpgsql';"
		res=`./psql1 "$@" -c "$sql"`

		if [[ "$res" == "t" || "$res" == "T" ]]
		then
			echo "OK: 'plpgsql' is installed as trusted"
			ext="0"
		else
			echo "Could not install 'plpgsql' as trusted."
			echo "Please verify your admin privileges and try again."
			ext="1"
		fi
	fi
else
	echo ""
	echo "Usage:"
	echo "    $0 [-h HOST] [-p PORT] [-d DATABASE]"
fi

echo ""
exit $ext

