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

WHOAMI=$(basename $0)

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.  Is PostgreSQL running?"
fi

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


ROLE=
LOG_ERRORS=false
LOG_TAG="${WHOAMI}"
while [ "$1" ]
do
    case "$1" in
	--role)
	    if [ ! "$2" ]
	    then
		die "The --role switch requires an argument."
	    fi
	    ROLE="SET ROLE '$2';"
	    shift 2
	    ;;
	--log-errors)
	    if [ ! "$2" ]
	    then
		die "The --log-errors switch requires an argument."
	    fi
	    LOG_ERRORS=true
	    LOG_TAG=$2
	    shift 2
	    ;;
	*)
	    # Anything not looking like an option is plain old
	    # arguments.  The end.
	    break
	    ;;

    esac
done

PGOPTIONS="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 "${PGOPTIONS} ${PSQL}" 2>$TMPBASE.error
    STATUS=$?
else
    (echo "${ROLE}" && cat "$@") \
	| ${PGOPTIONS} ${PSQL} 2>$TMPBASE.error
    STATUS=$?
fi

if [ "$STATUS" -ne 0 ]
then
    cat $TMPBASE.error 1>&2
    if ${LOG_ERRORS}
    then
	logger --priority error --tag "${LOG_TAG}" --file $TMPBASE.error 
    fi
    exit $STATUS
fi

exit 0
