#! /bin/bash

PGM=tr_start_nstx
USAGE="usage: $PGM shot try dir user [tshare]"

#@! Check arguments
#@! ---------------

if [ $# -lt 5 ] ; then
  echo $USAGE 1>&2
  exit 1
fi
. /u/pshare/globus/.userrc
pppl="TRUE"

shot=$1
try=$2
dir=$3
user=$4
runid=${shot}${try}

if [ $# -eq 5 ] ; then
   if [ $5 = "tshare" ]; then 
      tshare="tshare"
   fi
fi
# extract email
pshr=`whoami`
email=`grep $pshr /u/pshare/PSHR.LIST | cut -d: -f3 | sed 's/ *//g'`
if [ -z "$email" ]; then
   email=Transp_Support@pppl.gov
fi
echo "email = $email"

# jython+ is running in $TR_DISK = /p/transparch/tr_disk
if [ ! -d $dir ]; then
   echo "`pwd`/$dir does not exist"
   exit 1
fi
cd $dir

#printenv |sort
ls ${runid}*
# get Year and Write <runid>ID.TMP
set_yr $runid NSTX

echo $user > ${runid}.OWNER

#Handle proxy
#proxy=/u/$pshr/.globus/x509up_${user}.txt
#proxy=/u/$pshr/.globus/globus_gass_cache
#export X509_USER_PROXY=$proxy
#echo proxy = $X509_USER_PROXY

# need globus in $PATH
module load mdsplus
#echo GLOBUS_LOCATION = $GLOBUS_LOCATION
server="transpgrid.pppl.gov"
tree=transp_nstx
# >>>>> FIX  <<<<<
if [ ! -f ${runid}CC.TMP ]; then
   echo "comment missing" > ${runid}CC.TMP
fi
echo "env TR_EMAIL=$email tr_start.pl $server $tree $runid silent $tshare"
env TR_EMAIL=$email tr_start.pl $server $tree $runid silent $tshare
if [ $? = 0 ]; then
#   echo "tr_send_pppl.pl $runid NSTX NO_GLOBUS -s"
#   tr_send_pppl.pl $runid NSTX NO_GLOBUS -s

   ENQUEUE="/u/pshare/globus/transp_enqueue"
   pwd
   touch ${runid}_NSTX.beast
   echo "$ENQUEUE < ${runid}_NSTX.REQUEST"
   $ENQUEUE < ${runid}_NSTX.REQUEST
   if [ $? = 0 ]; then
      echo "submitted for pre-processing"
   else
      echo "transp_enqueue failed"
      exit 1
   fi
else
   echo "failed to create mdsplus tree"
   exit 1
fi
exit
