#!/bin/sh
# $PostgresPy: pl/plinit,v 1.9 2004/05/25 13:56:01 flaw Exp $
#
# † Instrument:
#     Copyright 2004, rhid development. All Rights Reserved.
#     
#     Usage of the works is permitted provided that this
#     instrument is retained with the works, so that any entity
#     that uses the works is notified of this instrument.
#     
#     DISCLAIMER: THE WORKS ARE WITHOUT WARRANTY.
#     
#     [2004, Fair License; rhid.com/fair]
#     
# Description:
#    An abstract language installer. Creates the handler,
#    validator, and language inside the specified database.
#    It also installs language specific utilities into a pl
#    schema.
#
# Usage:
#	plinit language version libpath [psql arguments...]
##
usage () { cat; } << EOU

plinit [-h] path_to_pl_library [psql options]

 -h   This help

If no psql options are specified,
SQL commands are sent to standard output.
EOU

while getopts "h" OPT
do
	case "$OPT" in
		*) usage; exit;;
	esac
done

PLNAME="$1"
PLVER="$2"
PATHTO="$3"
PL="$PLNAME$PLVER"
PLPATH="$PATHTO/$PL.so"
shift 3 || { usage; exit 1; }

exec << SQLEND
START TRANSACTION;
CREATE SCHEMA "${PL}";

CREATE FUNCTION "${PL}".handler()
RETURNS LANGUAGE_HANDLER LANGUAGE C
AS '$PLPATH','pl_handler';

CREATE FUNCTION "${PL}".validator(oid)
RETURNS VOID LANGUAGE C
AS '$PLPATH','pl_validator';

CREATE FUNCTION "${PL}".finalizer()
RETURNS VOID LANGUAGE C
AS '$PLPATH','pl_finalizer';

CREATE LANGUAGE "${PL}"
	HANDLER "${PL}".handler
	VALIDATOR "${PL}".validator;

CREATE VIEW "${PL}".proc AS
SELECT
	oid, *
FROM pg_proc
WHERE
	prolang = (SELECT oid FROM pg_language WHERE lanname = '${PL}');
COMMIT;
SQLEND

if test "$#" -gt 0
then
	psql "$@"
else
	cat
fi
