#!/bin/bash

cd $(dirname ${0})

source ./splitsetfunc

TRUE=1
FALSE=0
while getopts ":nl" opt; do
	case ${opt} in
		n)
			NOCONFIRM=${TRUE}
		;;
		*)	
	esac
done

shift $(( $OPTIND-1 ))

# give option 1 will bypass the check
if [[ ${NOCONFIRM} -ne ${TRUE} ]]; then
	echo "Confirm rebuild database yes/no"
	read ANSWER 
          case $ANSWER in
		[Yy][Ee][Ss] | [Yy] )
			echo "Database Rebuild Confirmed"
		;;
		*)
			echo "Database Rebuild Canceled"
			exit 1
		;;
          esac
fi

# define exit function
exit_timeout() {
  echo "Close all session before running this script."
  # timeout exit
  exit
}

# Handler for signal USR1 for the timer
trap exit_timeout SIGUSR1

# record own PID
export PID=$$

TIMEOUT=1
(sleep ${TIMEOUT} ; kill -SIGUSR1 $PID) &

# record PID of timer
TPID=$!

##################################
# Delete any existing database
##################################
echo "Dropping database ${database}..."
dropdb -U ${owner} ${database}

# NOTE: check for return status does not work
# here if database is in use or missing return status
# in both case equal to 0

#################################
# Kill timer pid if dropdb returns
#################################
kill ${TPID}

##################################
# Create the Dosis database
##################################
echo "Creating database ${database}..."
createdb -O ${owner} -U ${owner} ${database}

RESULT=${?}
if [[ ${RESULT} -ne 0 ]]; then
	exit ${RESULT}
fi

##################################
# Create the procedural language
##################################
echo "Adding procedural language"
# Must be superuser to add lanugague, so use postgres
${psql} -U postgres --quiet ${database} < language.sql

##################################
# Create the table structure
##################################
echo "-------------Inputting splitrxSchema.sql-----------------"
${psql} ${psqlargs} ${database} < splitrxSchema.sql

##################################
# Add default data
##################################
echo "-------------Adding SplitRx Default Data-----------------"
${psql} ${psqlargs} ${database} < defaultSplitRxData.sql

########################################
# Update permissions on tables
########################################

setPerms manchac