#! /bin/bash
cyflexlogevent -t generic -m 1 -m "script" -m "$0" 

# This script starts the external data manager for DARTS data loading.
#
# The main feature is that this insures that only one instance at a time
# is running.  If an instance is already running, it will be killed and
# a new instance started.
#
# If two instances are running at a time, it is possible to get
# errors.  One instance could start loading a file, then the
# second instance also starts loading it.  The 1st instance successfully
# loads the file.  The 2nd instance gets an error because it is trying 
# to access a file which the 1st instance deleted.
#
# Usage: /cyflex/cmds/start_darts_loading
#
# Author: Rob Janes
# 
# History
#   07/23/15 - Rob Janes - Initial release.

# This requires 1 command line argument, an existing configuration file.
if (( $# != 1 )); then
   echo This program requires one command line argument, the spec file.
   exit 1
fi
if [ ! -e $1 ]; then
   echo The command line argument must be an existing file.
   exit 1
fi

LABEL=`grep cyflex.extdatman.instance_label $1 | cut -f2 -d\  `
if [ "$LABEL" = '' ]; then
   echo The property file must contain an entry for cyflex.extdatman.instance_label
   exit 1
fi

# If this is already running, terminate it.
stop_darts_loading $1

# Insure the transfer directory, usually located in /tmp, exists.  If
# not, create it.
# First find the location of the transfer directory from the property
# file.
TRANSFER=`grep cyflex.extdatman.transfer_directory $1 | grep -v '^#' | cut -f2 -d\ `
# If the transfer directory doesn't exist, create it.
if [ ! -e $TRANSFER ]; then 
   mkdir -p $TRANSFER
   # Notify the user and abort if there is an issue creating the
   # transfer directory.
   if (( $? != 0 )); then
      echo Failed to create $TRANSFER - process not started.
      exit 7  
   fi
fi

. configure_java

# Start the external data manager up.
DATE=`date +"%y%m%d"`

# Set up class path for Java.
BASE=$GUI
export CLASSPATH=$BASE/ExternalDataManager.jar\
:$BASE/specfilegui.jar\
:$BASE/facade.jar\
:$D3/jsch.jar\
:$D3/jcmdline.jar\
:$D3/protobuf.jar

# Actually execute the program.
chrt -o 0 java -DPropertiesFile=$1 -Xms256m -Xmx512m \
   com.cybermetrix.cyflex.extdatman.DARTSExtDatMan \
   -config=$1 \
   >> /data/errors/extdatman.${LABEL}.$DATE 2>&1 &
