#!/usr/bin/env bash

CURR_DIR=$(pwd)"/"
cd ../../build/

#Optional Arguments for running batches of tests.
#   These are meant to be specified by command line, but the :-{VAL} specifies the default to use.
#   Can change the default here as desired. Ex: Changing to 2 Services would be: NUM_SERV=${1:-2}
DBNAME=${1:-ag} # name of database table. can leave as default or change to whatever you prefer
ESIZE=${2:-A}

# Avoid multiple users fighting over same database if default name is used (hacky solution)
DBNAME="$DBNAME$USER"

MPI_HAMMER_PARAMS="mpiexec --mca btl_openib_allow_ib 1 --mca btl openib,self,vader --mca opal_warn_on_missing_libcuda 0 --bind-to numa --map-by numa -np 1 --timeout 129600"

### AG Gen Parameters. Please run the AG generator with the '-h' parameter to see all options. Adjust as desired.
AG_TASK_PARAMS=" -t 1 -q 1 -p -a 0.6 -z ${DBNAME}"

### Running

## Database Work
#Hammer
if [ "$(dnsdomainname)" = "hammer.esg.utulsa.edu" ]; then 
	#Database stored on node with port
	if psql -p 5240 -h compute03 ${DBNAME} -c '\q' 2>&1; then
		echo "Database ${DBNAME} exists. Dropping and recreating from dump."
	   
		psql -p 5240 -h compute03 postgres -c "DROP DATABASE "$DBNAME""
		psql -p 5240 -h compute03 postgres -c "CREATE DATABASE "$DBNAME" WITH OWNER = ag_gen"
		psql -q -p 5240 -h compute03 "$DBNAME" < schema.sql
	
	else
		echo "Database ${DBNAME} does not exist. Creating and importing from dump."
	   
 		psql -p 5240 -h compute03 postgres -c "CREATE DATABASE "$DBNAME" WITH OWNER = ag_gen"
		psql -q -p 5240 -h compute03 "$DBNAME" < schema.sql
	fi
#Local
else
	if psql ${DBNAME} -c '\q' 2>&1; then
		echo "Database ${DBNAME} exists. Dropping and recreating from dump."

		psql postgres -c "DROP DATABASE "$DBNAME""
		psql postgres -c "CREATE DATABASE "$DBNAME" WITH OWNER = ag_gen"
		psql -q "$DBNAME" < schema.sql
	else
		echo "Database ${DBNAME} does not exist. Creating and importing from dump."
	
		psql postgres -c "CREATE DATABASE "$DBNAME" WITH OWNER = ag_gen"
		psql -q "$DBNAME" < schema.sql
	fi
fi

## Running the scripts
# NOTE: Do not use 'bash -c' or 'eval' unless you fully understand shell parsing. We are building an array
# of arguments dynamically to avoid wordsplitting and wildcard expansions
CMD=()
CMD+=$MPI_HAMMER_PARAMS
CMD+=" ./ag_gen -n "
CMD+=${CURR_DIR}"Employee_"${ESIZE}/"dmca.nm"
CMD+=" -x "
CMD+=${CURR_DIR}"Employee_"${ESIZE}/"dmca.xp"
CMD+=${AG_TASK_PARAMS}
${CMD}
