#!/bin/bash 
# Wraps psql for easier use.
# 
# As psql-exec, runs with no non-error output 
# As psql-query, runs with full output
#
# hb - changed from original psql-query


#PGVER=9.0
#PSQL=/usr/lib/postgresql/"$PGVER"/bin/psql
#PSQL=/usr/pgsql-$PGVER/bin/psql
PSQL=/usr/bin/psql
command -v "$PSQL" > /dev/null || error "$PSQL: can't execute"

# Append DB host if exist..
[ -z "$DB_HOST" ] && DB_HOST="localhost"
# Append DB password if exist..
[ -n "$DB_PASSWORD" ] && export PGPASSWORD="$DB_PASSWORD"

case "$0" in
	*-exec) export PGOPTIONS="$PGOPTIONS -c client_min_messages=error"; exec >/dev/null ;;
	*-query)  ;;
	*) error "$0: unrecognised program name" ;;
esac

if [ "$UID" != 0 ]; then
  if [ -n "$DB_USER" ]; then
    CMD=("$PSQL" -h "$DB_HOST" -U "$DB_USER" -d netx)
  else
    CMD=("$PSQL" -h "$DB_HOST" -d netx)
  fi
else
  if [ -n "$DB_USER" ]; then
    User="$DB_USER"
  else
    User=postgres
  fi
	##CMD="$PSQL -U $User -d netx"
        CMD=(su -s "$PSQL" "$User" -- -d netx)
fi

##CMD="$CMD -Aqt -v ON_ERROR_STOP="
##        echo "CMD2 - "  "${CMD[@]}" "$@"
##echo "CMD2 - " $CMD "$*"
##exec $CMD "$*"

 CMD=("${CMD[@]}" -Aqt -v ON_ERROR_STOP=)
 ##hb       echo "CMD2 - "  "${CMD[@]}" "$@"
 ret=1
 
COUNTER=0

 while [ $ret -ne 0 ]; do
	 "${CMD[@]}" "$@"
	 ret=$?
       ## echo "psql status -" $ret
       let COUNTER=$COUNTER+1
       if [ $COUNTER -gt 25 ]; then
          break
       fi
	   ## retry only in connectivity to DB problem(status 2)
       if [ $ret -ne 2 ]; then
            ret=0
       fi

done	 

