#! /bin/bash

case $DEBUG in
  1) set -x
     ;;
  *)
     ;;
esac

error() { # juste pour usage
    echo $1 1>&2
}

usage() {
    error "usage : exec-sql.sh [-h] -H <host> -d <dbname> -u <user> -p <password> [ -f <sql file> || -c <sql command> ] -F<separator> -o <output> -l <log file>"
    error "example : exec-sql.sh -H bonnie -d barbie -u pimengest -p "" -f schema.sql -F'|' -header -o output.lst -l exec-sql.log"
}

separator='|'
csql=0
header="-t"

while true
do
    case $1 in
	-o) output="$2"
	    shift 2
	;;
	-F) separator="$2"
	    shift 2
	;;
	-f) file="$2"
	    shift 2
	;;
	-c) file="/tmp/csql_$$.sql"
	    echo "$2" > $file
	    csql=1
	    shift 2
	;;
	-H) host="$2"
	    shift 2
	;;
	-u)	user="$2"
	    shift 2
        ;;
	-p) password="$2"
	    shift 2
        ;;
	-d) dbname="$2"
	    shift 2
	;;
	-l) logfile="$2"
	    shift 2
	;;
	-header) header=""
	    shift 1
	;;
	-h) usage
	    exit 0
	;;
	*)
	    break
	;;
  esac
done

if [ -z "$dbname" -o -z "$host" -o -z "$user" -o -z "$logfile" -o -z "$file" ] 
then
    usage
    exit 1
fi

date=`date '+%d-%m-%Y'`
error() {
    echo "ERROR:exec-sql.sh:$date: $1" 1>&2
    echo "ERROR:exec-sql.sh:$date: $1" >> $logfile
}

psqllog=/tmp/psql_$$.log

if [ -z "$output" ]
then
    send-user-password.sh -p $password | psql -h $host -f $file $dbname -U $user $header -A -F "$separator" 2> $psqllog
else
    send-user-password.sh -p $password | psql -h $host -f $file $dbname -U $user $header -A -F "$separator" -o $output 2> $psqllog
fi

if [ $? -eq 0 ]
then
    grep ERROR $psqllog > /dev/null 2>&1
    if [ $? -eq 0 ]
    then
	error "cannot exec $file in $dbname@$host"
	error "ERROR PSQL :"
	error "`grep ERROR $psqllog`"
	exit 1
    fi
else
    error "cannot exec $file in $dbname@$host"
    exit 1
fi

rm -f $psqllog
if [ $csql -ne 0 ]
then
    rm -f $file
fi

