#!/bin/sh

bin_dir=`dirname $0`
#function for generating sql
source $bin_dir/makeSQLData

#########
#DB VARS
#########
db_name=testdb
db_user=postgres
db_url_base="jdbc:postgresql://localhost/"
table_name=person
app_user=admin
app_user_pwd=secret
ddl_file=$bin_dir/makeTestDB.sql
dml_file=$bin_dir/makeData.sql

##########################
#Java Properties File vars
##########################
props_file="$bin_dir/../etc/rodexdon.properties"

#############
# Other vars
#############
#psql_cmd="psql -U $app_user -W -d $db_name "
psql_cmd="psql -U $app_user -d $db_name "


if [ -e "$ddl_file" ]
then
 rm -f $ddl_file
fi

echo "Creating database $db_name via the '$db_user' account.
I am assuming *local* database and its '$db_user' user can  
access it without password!"

echo "DROP DATABASE $db_name;" >> $ddl_file
echo "CREATE DATABASE $db_name;" >> $ddl_file
echo "ALTER DATABASE $db_name OWNER TO $app_user;" >> $ddl_file
psql -U $db_user -d test -f $ddl_file

#create table
echo "Executing DDL scripts for $db_name via the '$app_user' user account"
$psql_cmd -c "CREATE TABLE $table_name(id numeric PRIMARY KEY, name varchar, yob numeric);"

#test
echo "Testing connection..."
$psql_cmd -c "select count(*) from $table_name;" 

#populuate data
echo "Executing DML scripts for $db_name via the '$app_user' user account"
if [ -z "$1" ]
then
  num_rec=$def_num_recs
else 
  num_rec=$1
fi

make_dml_script $num_rec $dml_file

echo "Inserting $num_rec records..."
$psql_cmd -f $dml_file


#Generate a Java properties file for the application
echo "Generating a Java properties file for the application"
ttl=3600000
id_min=1
id_max=$((id_min+num_rec-1))
id_num_range=2
yob_min=$((min_yob+id_min))
yob_max=$((yob_min+num_rec-1))
yob_num_range=3

if [ -e "$props_file" ]
then
 rm -f $props_file
fi

echo "// db vars" >> $props_file
echo "DB_NAME $db_name" >> $props_file
echo "DB_USER $app_user" >> $props_file
echo "DB_PWD $app_user_pwd" >> $props_file
echo "URL_BASE $db_url_base" >> $props_file
echo "TTL $ttl" >> $props_file
echo "NUM_SUB_RANGES_ID $id_num_range" >> $props_file
echo "DOMAIN_ID_MIN $id_min" >> $props_file 
echo "DOMAIN_ID_MAX $id_max" >> $props_file 
echo "NUM_SUB_RANGES_YOB $yob_num_range" >> $props_file 
echo "DOMAIN_YOB_MIN $yob_min" >> $props_file
echo "DOMAIN_YOB_MAX $yob_max" >> $props_file


