#!/bin/bash

####################################################################################
## This script reads sql insert commands from a file and sends them
## to Jaguar server
##
##  ./jagimportsql <InsertSQLFile>
##
##  For example:
##   ./jagimportsql insert.sql
##
##  where file insert.sql contains these lines:
##    insert into  mydb.table ( col1, col2, col3 ) values ( 'k1', 'm1', 'vvv1' ); 
##    insert into  mydb.table ( col1, col2, col3 ) values ( 'k2', 'm2', 'vvv2' ); 
##    insert into  mydb.table ( col1, col2, col3 ) values ( 'k3', 'm3', 'vvv3' ); 
####################################################################################


if [[ -f "$HOME/.jaguarhome" ]]; then
    export JAGUAR_HOME=`cat $HOME/.jaguarhome`
else
    export JAGUAR_HOME=$HOME/jaguar
fi

un=`uname -o`
if [[ "x$un" = "xMsys" ]] || [[ "x$un" = "xCygwin" ]]; then
    jqlbin=jql.exe
else
    jqlbin=jql.bin
fi


dbname=""
outfile=""
while getopts "d:t:f:h" opt; do
  case $opt in
    d)
	  dbname=$OPTARG
      ;;
    f)
	  sqlfile=$OPTARG
      ;;
    h)
	  echo "$0  -d DATABASE -t TABLE"
	  exit 1
      ;;
    \?)
      echo "Invalid option: $OPTARG" 
	  echo "$0  -d DATABASE -t TABLE"
      exit 1
      ;;
    :)
      echo "Option $OPTARG requires an argument." 
	  echo "$0  -d DATABASE -t TABLE"
      exit 1
      ;;
  esac
done

if [[ "x$dbname" = "x" ]]; then
	echo "$0 -d DB -f <InsertSQLFile>"
	echo "Please provide database name "
	exit 1
fi

if [[ "x$sqlfile" = "x" ]]; then
	echo "$0 -d DB -f <InsertSQLFile>"
	echo "Please provide insert-formatted SQL file"
	exit 1
fi

pass=$ADMIN_PASSWORD
if [[ "x$pass" = "x" ]]; then
    echo -n "Please enter admin password: "
    read -s pass
    echo
fi

port=`grep PORT $JAGUAR_HOME/conf/server.conf |grep -v '#' | awk -F= '{print $2}'`
host=localhhost
date
bytes=`stat -c %s $sqlfile`
echo "$sqlfile has $bytes bytes "
$JAGUAR_HOME/bin/$jqlbin -u admin -p $pass -d $dbname -h localhost:$port -n -q < $sqlfile
echo "Done"
date
