#! /bin/bash

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

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

usage() {
		error "usage : destroy-db.sh [-h] -H <host> -d <dbname> -u <user> -p <password> -l <log file>"
		error "example : destroy-db.sh -H bonnie -d barbie -u pimengest -p "" -l destroy-db.log"
}

while true
do
  case $1 in
		-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
				;;
    -h) usage
				exit 0
				;;
     *)
				break
				;;
  esac
done

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

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

psqllog=/tmp/psql_$$.log

send-user-password.sh -p $password | dropdb -h $host $dbname -U $user -W > $psqllog 2>&1
if [ $? -eq 0 ]
then
	grep ERROR $psqllog > /dev/null 2>&1
	if [ $? -eq 0 ]
	then
		error "cannot destroy $dbname@$host"
		error "ERROR PSQL :"
		error "`grep ERROR $psqllog`"
		exit 1
	fi
else
	error "cannot destroy $dbname@$host"
	exit 1
fi

rm -f $psqllog

