#!/bin/sh -
# 
# This script reads and writes entries from a database. 
# Examples:
# writedb_entry -help
# writedb_entry -s Pf3D7_01 Pf3D7_05 Pf3D7_07
#

#if [ -z "$ARTEMIS_HOME" ]; then
#  PRG=`readlink -f "$0"`
#  echo $PRG
#  ARTEMIS_HOME=`dirname "$PRG"`/..
#fi

PRG=$0
progname=`basename $0`

while [ -h "$PRG" ] ; do
  ls=`ls -ld "$PRG"`
  link=`expr "$ls" : '.*-> \(.*\)$'`
  if expr "$link" : '.*/.*' > /dev/null; then
    PRG="$link"
  else
    PRG="`dirname $PRG`/$link"
  fi
done

ARTEMIS_HOME=`dirname "$PRG"`/..

CLASSPATH="$ARTEMIS_HOME:$ARTEMIS_HOME/lib/biojava.jar:$ARTEMIS_HOME/lib/jemAlign.jar:$ARTEMIS_HOME/lib/jakarta-regexp-1.2.jar:$ARTEMIS_HOME/lib/macos.jar:$ARTEMIS_HOME/lib/postgresql-8.4-701.jdbc3.jar:$ARTEMIS_HOME/lib/chado-14-interface.jar:$CLASSPATH"

# iBatis jars
CLASSPATH="$CLASSPATH:$ARTEMIS_HOME/lib/ibatis/ibatis-2.3.4.726.jar:$ARTEMIS_HOME/lib/ibatis/:$ARTEMIS_HOME/lib/ibatis/log4j-1.2.14.jar:$ARTEMIS_HOME/lib/ibatis/cglib-nodep-2.2.jar:$ARTEMIS_HOME/lib/retrotranslator-runtime-1.1.0.jar"
CLASSPATH="$CLASSPATH:$ARTEMIS_HOME/lib/picard/picard.jar"
export CLASSPATH

FLAGS="-mx2048m -ms20m -Djdbc.drivers=org.postgresql.Driver -Dibatis"
DEFAULT_CONNECTION="-Dchado=db.genedb.org:5432/snapshot?genedb_ro -Dread_only"

while test $# != 0
    do
    case $1 in
    -Dchado*)
       DEFAULT_CONNECTION="$1" ;;
    -D*) 
       FLAGS="$FLAGS $1" ;;
    *) break ;;
    esac
    shift
done

# searches for the -c option (needs to know the index)
idx=0
for arg in "$@"
do
	if [ '-c' == "${arg}" ]; then
		let "nextID = $idx + 1";
		DEFAULT_CONNECTION="-Dchado=${!nextID}"		
	fi
	if [ '-l' == "${arg}" ]; then
		let "nextID = $idx + 2";
                eval MAPPING_PATH="${!nextID}"
		CLASSPATH="${MAPPING_PATH}:$CLASSPATH"
		export CLASSPATH
	fi
	let idx++
done

echo starting to write with flags: $DEFAULT_CONNECTION $FLAGS 1>&2

java $DEFAULT_CONNECTION $FLAGS uk.ac.sanger.artemis.io.ReadAndWriteEntry "$@"
