#!/bin/sh
#
# postgresql-load - Run a SQL file through psql
#
# See manual page for documentation.
#

die()
{
    echo "$@" 1>&2
    exit 1
}


TMPBASE=${TMP:=/tmp}/$(basename $0).$$

cleanup()
{
    rm -rf $TMPBASE/*
}
trap cleanup EXIT


PG_USER=$(ps -e -o 'user,command' \
    | awk '$2 == "postgres:" { print $1 }' \
    | sort \
    | uniq )
if [ -z "${PG_USER}" ]
then
    die "Unable to determine PostgreSQL user."
fi

[ "$(id -nu)" = "${PG_USER}" -o "$(id -u)" = "0" ] \
    || die "This program must be run as root or ${PG_USER}"



if [ "$1" = '--role' ]
then
    shift
    if [ $# -eq 0 ]
    then
	die "The --role switch requires an argument"
    fi

    ROLE="SET ROLE '$1';"
    shift
fi


export PGOPTIONS="--client-min-messages=WARNING"
PSQL="psql -q -v ON_ERROR_STOP=1"

if [ "$(id -u)" = "0" ]
then
    (echo "${ROLE}" && cat "$@") \
	| su - "${PG_USER}" -c "${PSQL}" 2>$TMPBASE.error
    STATUS=$?
else
    (echo "${ROLE}" && cat "$@") \
	| ${PSQL} 2>$TMPBASE.error
    STATUS=$?
fi

if [ "$STATUS" -ne 0 ]
then
    cat $TMPBASE.error 1>&2
    exit $STATUS
fi

exit 0
