#!/bin/sh -x
#----------------------------------------------------------------------
#
# Name: flush_now.sh
#
# Description:
#	Script invoked by an OSF trigger.
#
#	If no existing OTFC_response is found, one is created
#	by copying the OTFC_request and altering the STATUS field.
#	If successful, exit with status = GO_FLUSH, which will result in the
#	OSF being set to begin the error flush pipeline stage.
#
#--------------------------------------------------------------------
#                          REVISION HISTORY
#--------------------------------------------------------------------
#            PR
#   DATE   NUMBER  User  Description
# -------- ------  ------ -------------------------------------
# 11/29/01 xxxxx   MSwam  for ST-ECF (immediate flushing after error detection)
# 04/04/03 43915   WMiller DADS 10.0 support
#
#----------------------------------------------------------------------
banner=">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"
echo $banner
date
#
# define EXIT status values
timer_expired=2   #exit status will cause OSF to move to flush stage
quit_this_dataset=1    #exit status will cause error in OSF for this dataset

# parse directory,instrument_code from OSF fields
p_dset=`echo $OSF_DATASET | awk '{n=split($1,a,"_");print a[2]}'`
p_inst=`echo $p_dset | awk '{a=substr($1,1,1);print a}'`
p_otfcid=`echo $OSF_DATASET | awk '{n=split($1,a,"_");print a[1]}'`
p_dir=$OSF_DATASET

# set calibration directory 
basedir=`osfile_stretch_file $ALL_BASE_DIR`
echo "$basedir"

# set cwd to dataset directory
cd $basedir/$p_dir
if [ $? != 0 ]
then
   echo "ERROR: Failed to set directory to $basedir/$p_dir"
   echo $banner
   exit $quit_this_dataset
fi

# create response file by copying and editing the OTFC_request
request_filename=./$OSF_DATASET$OTFC_REQUEST_EXT
if [ ! -f $request_filename ]
then
   echo "ERROR: OTFC_request_file $request_filename not found."
   echo $banner
   exit $quit_this_dataset
fi
rsp_filename=./$OSF_DATASET$OTFC_RESPONSE_EXT
egrep -v "END_FILE|STATUS=" $request_filename > $rsp_filename
#
echo "STATUS=STUCK" >> $rsp_filename
echo "END_FILE" >> $rsp_filename

# register error in stats relation
db_otfr_stats_e.pl $p_otfcid $p_dset

echo "FLUSHING $rsp_filename "
echo $banner
exit $timer_expired
