#!/bin/bash

####################################################################################
## This script connects to jaguar server and imports the temp files created by jagexport
## import the data back to the table.
##
##  ./jagimport -d  DATABASE  -t TABLE
##
##  For example:
##  ./jagimport -d  mydb  -t cardtable
##
####################################################################################

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=""
tabname=""
while getopts "d:t:h" opt; do
  case $opt in
    d)
	  dbname=$OPTARG
      ;;
    t)
	  tabname=$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 "Error: database is not provided"
	echo "$0  -d DATABASE -t TABLE"
	exit 1
fi

if [[ "x$tabname" = "x" ]]; then
	echo "Error: table is not provided"
	echo "$0  -d DATABASE -t TABLE"
	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
sql="import into $dbname.$tabname"
$JAGUAR_HOME/bin/$jqlbin -u admin -p $pass -d $dbname -h localhost:$port -e "$sql" -v 
echo "Done"
echo "Please make sure that the imported data is written to the table successfully."
echo "If import is successful, please issue this command to clean up temporary files:"
echo "$JAGUAR_HOME/bin/jagimportcomplete -d $dbname -t $tabname"
date

