#!/bin/bash

####################################################################################
## This script connects to jaguar server and creates temp files
## on each server in the cluster. They are ready for jagimport command to
## import the data back to the table.
##
##  ./jagexport -d  DATABASE  -t TABLE
##
##  For example:
##  ./jagexport -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
$JAGUAR_HOME/bin/$jqlbin -u admin -p $pass -d $dbname -h localhost:$port -e "select * from $tabname export" -v 
echo "Done"
echo "Exported data is saved on each host in the cluster."
echo "The exported file can be imported back to database with the command:"
echo
echo "    ./jagimport -d $dbname -t $tabname"
echo
date

