#!/bin/bash

####################################################################################
## This script connects to jaguar server and dumps a table data to output csv file
## to Jaguar server. The output file is OUTFILE after -f. If not provided, it is
## DATABASE.TABLE.csv
##
##  ./jagexportcsv -d  DATABASE  -t TABLE  -f [OUTFILE]
##
##  For example:
##  ./jagexportcsv -d  mydb  -t cardtable -f out.csv
##  ./jagexportcsv -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=""
outfile=""
while getopts "d:t:f:h" opt; do
  case $opt in
    d)
	  dbname=$OPTARG
      ;;
    t)
	  tabname=$OPTARG
      ;;
    f)
	  outfile=$OPTARG
      ;;
    h)
	  echo "$0  -d DATABASE -t TABLE"
	  exit 1
      ;;
    \?)
      echo "Invalid option: $OPTARG" 
	  echo "$0  -d DATABASE -t TABLE [-f OUTFILE]"
      exit 1
      ;;
    :)
      echo "Option $OPTARG requires an argument." 
	  echo "$0  -d DATABASE -t TABLE [-f OUTFILE]"
      exit 1
      ;;
  esac
done

if [[ "x$dbname" = "x" ]]; then
	echo "Error: database is not provided"
	echo "$0  -d DATABASE -t TABLE [-f OUTFILE]"
	exit 1
fi

if [[ "x$tabname" = "x" ]]; then
	echo "Error: table is not provided"
	echo "$0  -d DATABASE -t TABLE [-f OUTFILE]"
	exit 1
fi

if [[ "x$outfile" = "x" ]]; then
    outfile=${dbname}.${tabname}.csv
fi
dn=`dirname $outfile`
if [[ ! -w "$dn" ]]; then
    echo "Directory $dn is not writable, exit"
    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
cmdfile=jagexport.cmd.$$
echo "spool $outfile;" > $cmdfile
echo "select * from $tabname timeout 1000000 exportcsv;" >> $cmdfile
echo "spool off;" >> $cmdfile
echo "quit;" >> $cmdfile
echo 
$JAGUAR_HOME/bin/$jqlbin -u admin -p $pass -d $dbname -h localhost:$port -v  < $cmdfile
echo "Done"
echo "Exported CSV data is saved in $outfile"
echo "The exported file can be imported back to database with the command:"
echo
echo "    ./jagimportcsv -d $dbname -t $tabname -f $outfile"
echo
/bin/rm -f  $cmdfile
date

