#!/bin/sh

# Create the article-p2p database with two tables

bin_dir=`dirname $0`
etc_dir="$bin_dir/../etc"

echo "bin dir = $bin_dir; etc dir = $etc_dir"

#########
#DB VARS
#########
db_name=articlep2p
db_user=nr600
db_url_base="jdbc:postgresql://localhost"
app_user=nr600
app_user_pwd=secret
ddl_file=$bin_dir/makeTestDB.sql
table_name=article # test table name

##########################
#Java Properties File vars
##########################
props_file="$etc_dir/sdi.properties"

#############
# Other vars
#############
#psql_cmd="psql -U $app_user -W -d $db_name "
psql_cmd="psql -U $app_user -d $db_name "
bibfile=$etc_dir/p2p.bib

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 the '$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 tables and populate data
##################################
set -x
java -cp ${CLASSPATH}:lib/dblibrary.jar db.lib.XMLSQLInterpreter -user $app_user -password $app_user_pwd -driver org.postgresql.Driver -url $db_url_base/$db_name $etc_dir/articlep2p.xml

set +x

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

###############################################
# extract articles and books from bibtex file
###############################################
#read in the extracted files and create db entries from them
$bin_dir/parsebib $bibfile

# insert db entries into database
for sqlfile in `ls $etc_dir/*.sql`
do
  echo "Inserting data from $sqlfile into db..."
  $psql_cmd -f $sqlfile
done

#Generate a Java properties file for the application

