#!/bin/sh -x
##########################################################################
#
# routine: rspxxx.sh 
#
# purpose: Script to create OTFC_response and copy it to DADS.
#
#       The response file is not given its proper filename until
#       it is copied to the DADS system.  This allows this stage
#       to be rerun without hand changes, should a failure occur.
#
# modification history:
#
#   date     opr    who       reason
# -------- -------- --------- --------------------------------------
# 09/22/98 36848    MSwam     first version
# 10/20/98 36860    MSwam     use -pw option for netcopy 
# 11/23/98 37814    MSwam     use -safe_copy to transfer response file
# 12/04/98 35081    MSwam     new format for request filename
# 04/09/99 38834    MSwam     add banner print
# 12/23/99 39366    MSwam     add call to fill otfc_stats relation
# 03/16/00 40129_03 MSwam     change EVNT to EVENT for OAPI
# 01/31/01 43165    MSwam     mods for OTFR
# 02/14/01 43165_01 MSwam     adjust ASN ending character test   
# 05/17/01 43920    MSwam     adjust singleton osf test
# 11/26/01 44598_01 MSwam     parameterize calibration stage name
# 04/23/02 44741    WMiller   use getpasswd
# 06/10/02 43915    WMiller   use cp in place of netcopy
# 08/21/03 48370    Sherbert  Add missing "-1" param to ls
#
##########################################################################
banner=">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"
echo $banner
date
#
go_absent=102          #this exit status is in the FATAL range for XPOLL
quit_this_dataset=1    #this exit status is mapped and will allow
                       #  the process to try another dataset
all_is_well=0
#
# OSF TRIGGER: Normal mode of processing 
#
# parse dataset,directory from OSF field
p_dset=`echo ${OSF_DATASET} | awk '{n=split($1,a,"_");print a[2]}'`
p_dir=$OSF_DATASET
p_otfcid=`echo $OSF_DATASET | awk '{n=split($1,a,"_");print a[1]}'`

#
# resolve stretch for UNIX
caldir=`osfile_stretch_file $OUTPATH`
if [ ! -d $caldir/$p_dir ] 
then
   echo "ERROR: $caldir/$p_dir directory does not exist"
   exit $go_absent
fi
cd $caldir/$p_dir
if [ $? != 0 ]
then
   echo "ERROR: Failed to set directory to $caldir/$p_dir"
   exit $go_absent
fi
localdir=`pwd`
echo "sitting in $localdir"
#
# recompute the file count and update the request file
# (the awk pipe is necessary after wc to left-justify the wc output)
#
new_count=`ls -1 ./*.fits | wc -l | awk '{print $1}'`
old_count=`awk -F= '/FILE_COUNT/ {print $2}' ./${OSF_DATASET}$REQUEST_FILEEXT`
sed -e "s/FILE_COUNT=$old_count/FILE_COUNT=$new_count/g" ./${OSF_DATASET}$REQUEST_FILEEXT > ./tmp$$.req
if [ $? != 0 ]
then
    echo "ERROR: failed to update FILE_COUNT in ${OSF_DATASET}$REQUEST_FILEEXT"
    exit $quit_this_dataset
fi
mv ./tmp$$.req ./${OSF_DATASET}$REQUEST_FILEEXT
if [ $? != 0 ]
then
    echo "ERROR: failed to rename from tmp$$.req to ${OSF_DATASET}$REQUEST_FILEEXT"
    exit $quit_this_dataset
fi
#
# determine if exposure requested is an ASN by last character of ipppssoot
lastchar=`echo $p_dset | awk '{a=substr($1,length,1); print a}'`
case $lastchar in
[0-9a-i]) 
      # if an ASN, replace last character with zero to search for
      # primary product (sub-products don't have an OSF in the science pipe)
      ipppssoo=`echo $p_dset | awk '{a=substr($1,1,8); print a}'`
      searchval=$ipppssoo"0"
      #
      # test OSF to get status of calibration pipeline stage
      calstatus=`osf_test -p $DATA_REDUCTION_PATH -f $searchval -pr $CAL_STAGE_NAME`

      ;;
*)
      # use a wildcard for the last character of the ipppssoot
      searchval=`echo $p_dset | awk '{a=substr($1,1,8); print a}'`
      #
      # test OSF to get status of calibration pipeline stage
      calstatus=`osf_test -p $DATA_REDUCTION_PATH -f $searchval\? -pr $CAL_STAGE_NAME`

      ;;
esac
if [ $? != 0 ]
then
   echo "ERROR: osf_test failed to query status value"
   exit $quit_this_dataset
fi
#
# create new request file without status or ending lines
egrep -v "END_FILE|STATUS=" ./${OSF_DATASET}$REQUEST_FILEEXT > tmp$$.req
#
# append STATUS to the OTFC request, if defined
cal_success=F
if [ "$calstatus" ]
then
   # a "c" in the calibration status means success
   echo $calstatus | grep c > /dev/null
   if [ $? = 0 ]
   then
      echo "STATUS=$RESPONSE_STATUS_OK" >> tmp$$.req
      cal_success=T
   else
      # calibration incomplete or in error, return NOCAL
      echo "STATUS=$RESPONSE_STATUS_NOCAL" >> tmp$$.req
   fi
else
   # calibration stage undetermined, return NOCAL
   echo "STATUS=$RESPONSE_STATUS_NOCAL" >> tmp$$.req
fi
echo "END_FILE" >> tmp$$.req

#
# copy response file for restartability
cp tmp$$.req ./${OSF_DATASET}$REQUEST_FILEEXT
if [ $? != 0 ]
then
   echo "WARNING: failed to copy tmp$$.req to ${OSF_DATASET}$REQUEST_FILEEXT"
fi

#
# rename new response file for transfer to DADS 
mv tmp$$.req ./${OSF_DATASET}$RESPONSE_FILEEXT 
if [ $? != 0 ]
then
   echo "ERROR: failed to rename tmp$$.req to ${OSF_DATASET}$REQUEST_FILEEXT"
   exit $quit_this_dataset
fi

#
# copy the OTFC_response to a remote DADS directory (using cp + mv
#   since DADS polls for this file)
#
cp $localdir/${OSF_DATASET}${RESPONSE_FILEEXT} $RESPONSE_DIRECTORY/${OSF_DATASET}${RESPONSE_FILEEXT}${TMP}
mv $RESPONSE_DIRECTORY/${OSF_DATASET}${RESPONSE_FILEEXT}${TMP} $RESPONSE_DIRECTORY/${OSF_DATASET}${RESPONSE_FILEEXT}
save_stat=$?
if [ $save_stat != 0 ]
then
       echo "ERROR: Failed file copy; status = $save_stat"
       echo "Unable to send OTFC response for $OSF_DATASET to $RESPONSE_DIRECTORY"
       exit $quit_this_dataset
else
       echo "file copy complete."
fi

#
# save time response was sent to DADS
resp_time=`date +"%d-%b-%Y %T"`

#
# determine disk space used by all FITS files 
disk_space=`du -ks *.fits | awk '{sum += $1}END{print sum}'`

# update OTFC stats in database
db_otfr_stats_rs.pl $p_otfcid $p_dset $disk_space $new_count $cal_success "$resp_time"

#
# remove any leftover tmp files from restarts
rm tmp*

#
# complete, exit success
exit $all_is_well
