#! /bin/bash
#set -v
# This script starts the external data manager for file movement to the central
# node.
#
# 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_rapid_transfers
#
# Author: Rob Janes
# 
# History
#   07/23/15 - Rob Janes - Initial release.
#   09/13/16 - Joe Suever - Modified from Indicom PC to CyFlex 
#   10/05/16 - Nareeya Kaewfanapadon - Modified from
#      start_sftp_transfer for rapid transfer
#   12/23/24 - Rob Janes - Added to cyflex_java as standard process.

# 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_rapid_transfers $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\
:$D3/jsch.jar\
:$D3/jcmdline.jar\
:$D3/protobuf.jar

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