#!/bin/sh
trap "" 1 2 3 15
#******************************************************************************
#                              ISTP LZP SOFTWARE
#                      Property of the U.S. Government
#                              NASA/GSFC/Code 500
#******************************************************************************
#
#    UNIT NAME:  lzp_replay
#
#    PURPOSE:  To replay an FTP file through the LZP system
#
#    INVOCATION METHOD:  lzp_replay [opts] <ftp directory> <ftp input file>
#                                         <capture directory> <socket port>
#
#    ARGUMENT LIST:
#    Name            Type            Use  Description
#    --------------  --------------  ---  -----------
#    $1              string           I   full pathname of ftp directory
#    $2              string           I   simple filename of ftp input file
#    $3              string           I   full pathname of capture directory
#    $4              integer          I   DPS software input socket port number
#
#    EXTERNAL VARIABLES:
#    Source          Name            Type       Use  Description
#    --------------  --------------  ---------  ---  -----------
#    Bourne-Shell    $HOME           path        I   user's home directory
#    Bourne-Shell    $?              string     I/O  success = 0, else failure
#
#    EXTERNAL UNIT/MACRO/PROCEDURE/FUNCTION REFERENCES:
#    Name            Purpose
#    --------------  ----------------
#    none
#
#    ABNORMAL TERMINATION CONDITIONS, ERROR MESSAGES:
#    $? <> 0 when any stage of processing fails
#
#    ASSUMPTIONS, CONSTRAINTS, RESTRICTIONS:
#    see notes
#
#    DEVELOPMENT HISTORY:
#    Author           Change-ID        Release  Date      Description of Change
#    ---------------  ---------------  -------  --------  ---------------------
#    R. Wiechert      WIND970001       R1.0     07/25/97  Original code
#    R. Wiechert      WIND970001       R1.0     08/05/97  Determine FS config
#    R. Wiechert      WIND970001       R1.0     08/07/97  Modify replay parameters
#    R. Wiechert      WIND970001       R1.0     08/10/97  Modify file extensions
#    R. Wiechert      WIND970001       R1.0     08/19/97  Modify FS .cfg filenames
#    R. Wiechert      WIND970001       R1.0     09/02/97  Flag PWIW for a/d process
#    R. Wiechert      WIND970001       R1.0     09/18/97  FS .cfg files moved to
#                                                          /opt/local/lzp/bin/etc
#    D. Fink          WIND970001       R1.0     09/26/97  Added quicklook default
#                                                          for GEOTAIL  
#    D. Fink          WIND970001       R1.0     09/29/97  Made quicklook default
#                                                          for all missions
#    D. Fink          WIND970001       R1.0     10/02/97  Links for sw_sync reference
#                                                          cm/current/fs...
#    D. Fink          WIND970001       R1.0a    10/14/97  Added packetizer inputs
#                                                          and changed defaults.
#    D. Fink          WIND970001       R1.0c    11/30/97  Removed Quicklook defaults 
#                                                          for WIND/POLAR/PWIW
#    R. Wiechert      ISTP             R1.0c    12/31/97  Replace ftp_rename with
#                                                          /opt/local/bin/lzp_rename
#                                                          and implement .replayrc
#    R. Wiechert      ISTP             R1.0d    01/28/98  Add interactive hooks
#                                                          and convert to /bin/sh
#    R. Wiechert      ISTP             R1.2     04/21/98  Modify PK mission config
#                                                          options, sw_sync relocated
#                                                          to /opt/irts/bin
#    R. Wiechert      ISTP             R1.3     07/01/98  Enhanced various options.
#
#    NOTES:
#    This script is invoked by the DPS software in order to replay an FTP file
#    through the system in an automated fashion.  The environment variable
#    $FTP_REPLAY_SCRIPT should be set to the [path] name of this script, invoked
#    with the -f option.
#
#    The $FTP_REPLAY_SUFFIX environment variable determines which files will be
#    replayed by the DPS software.  If the $FTP_REPLAY_SUFFIX is set to "blk"
#    then only files matching the pattern *.blk will be replayed.  Continuing
#    with this example, DPS software will use the following conventions:
#
#    *.blk               =  ftp input file, pending replay
#    *.blk_replay        =  ftp input file, replay in progress
#    *.blk_replay_error  =  ftp input file, replay failed
#    *.blk_replay_log    =  ftp replay log, text output from subprocesses
#
#    DPS software will automatically manage files with the above extensions
#    once the ftp replay has been completed.  DPS software will not create,
#    archive, or delete any other files.  Therefore this script and its
#    subprocesses must be responsible for removing and otherwise managing
#    any other files which might be created as byproducts of the replay.
#
#    This script must perform the following actions in sequential order, without
#    returning until all replay processing is completed.  This script must supply
#    an exit status of success = 0, failure <> 0.
# 
#    - determine and create frame sync parameters
#    - invoke frame sync process
#    - determine and create packetizer parameters
#    - invoke packetizer process
#    - cleanup any and all intermediate files
#    - append messages to log file
#
#******************************************************************************
text_file_editor="/usr/dt/bin/dtpad -standAlone"
wait_sleep=5 # sleep in 5 second intervals
wait_log=300 # log status every 5 minutes
wait_timeout=86400 # timeout after 1 day
interactive=false # assume software driven
ignoreinput=false # process input file
sync_only=false # invoke A/D as well
ftp_lock_dir="$HOME/config"
ftp_config_dir="$HOME/config"
ftp_trend_dir="$HOME/trend"
ftp_archive_dir="$HOME/archive"
replayrc="$HOME/.replayrc"
help=false

# parse option flags
while getopts hisd:r:c:t:a: option
do
   case $option in
      i) interactive=true ;;
      s) sync_only=true ;;
      d) DISPLAY="$OPTARG"; export DISPLAY ;;
      r) replayrc="$OPTARG" ;;
      c) ftp_config_dir="$OPTARG" ;;
      t) ftp_trend_dir="$OPTARG" ;;
      a) ftp_archive_dir="$OPTARG" ;;
      *) help=true ;;
   esac
done

# display help as needed
shift `expr $OPTIND - 1`
if [ "$help" = "true" -o $# != 4 ]
then
more << END_USAGE_TEXT

USAGE:     lzp_replay [-his] [-d display] [-r replayrc]
                      [-c config] [-t trend] [-a archive]
                      <directory> <file> <capture> <socket>

PURPOSE:   To replay a telemetry file through the LZP system

OPTIONS:   -h      display help screen
           -i      interactive manual replay
           -s      stop after frame synchronizer completes
           -d      specify display terminal address
           -r      specify replayrc file name
           -c      specify configuration file directory
           -t      specify trend transfer directory
           -a      specify file archive directory

WARNING:   Only DPS software may invoke this script directly!
           If you are a human, please use lzp_process instead.

SYNOPSIS:  The -i option is used to specify interactive manual
           replays so that the user will be prompted to make
           miscellaneous decisions at various points during
           the replay.  In the default non-interactive mode
           the software will make decisions automatically
           without prompting the user for any input at all.

           The -s option is used to stop the replay after
           frame synchronization has been completed and is
           useful in generating amf files to be examined and
           edited manually before further processing.

           The -d option is used to specify an alternate
           display address to be used by subsystems which
           require a graphical user interface.  Except for
           interactive replays, the DISPLAY parameter in the
           replayrc file takes precedence.

           The -r option is used to specify an alternate
           replayrc file instead of the default .replayrc
           which is located in the home directory.  The
           replay rc file contains configuration parameters
           for multiple subsystems, including lzp_replay.

           The -cta options may be used to specify alternate
           config, trend, and archive directories instead of
           the defaults located in the home directory.  This
           allows the operator to switch between multiple
           config directories containing possibly different
           frame synchronizer configuration files.  Although
           the config directory must actually be a writable
           directory, the trend and archive directories may
           be specified as /dev/null in order to prevent the
           trending and archiving functions from occurring.

FILES:     The replayrc file, ~/.replayrc by default, is
           used to specify configuration parameters for
           multiple subsystems, including lzp_replay, which
           persist as long as the replayrc file does.  If
           no replayrc file exists then default behaviour
           is assumed.

           The replayrc file contains statements of the
           form "parameter=value;" where each statement
           must contain exactly one "=" separator and one
           ";" terminator.  Both parameters and values are
           case-sensitive.  Values may contain space and/or
           comma separated lists.  For example, statements
           affecting lzp_replay operation are:

           DISPLAY=150.144.182.76, 150.144.182.77;
           EDITOR=/usr/openwin/bin/xterm -e vi;
           IGNORE=A, B, C, D, E;
           TREND=NULL;

           The DISPLAY parameter is a list of display
           addresses to be attempted in order from left
           to right until an active display is found.
           In the absence of the DISPLAY parameter, the
           local host address is assumed.

           The EDITOR parameter is the command used to
           invoke the configuration file text editor,
           including options, but not arguments.  In the
           absence of the EDITOR parameter, the default
           editor is "/usr/dt/bin/dtpad -standAlone".

           The IGNORE parameter is a list of PDF's to be
           archived, but otherwise ignored.  PDF Z is
           always implied in addition, even if the value
           is specified as NULL.  In the absence of the
           IGNORE parameter, NULL (plus Z) is assumed.

           The TREND parameter is a list of PDF's to be
           forwarded for trending.  The value NULL may
           be used to prevent the trending function from
           occurring for any file.  In the absence of the
           TREND parameter, mission specific defaults are
           hardcoded into the lzp_replay script.

END_USAGE_TEXT
exit 1
fi


###############  PROGRAM INITIALIZATION  ###############


# validate options
for option in $ftp_config_dir $ftp_lock_dir
do
   if [ ! -d "$option" -o ! -x "$option" -o ! -r "$option" -o ! -w "$option" ]
   then
      echo "ERROR: lzp_replay: $option"
      exit 1
   fi
done

# parse input parameters
ftp_input_dir=$1
ftp_input_file=$2
ftp_capture_dir=$3
ftp_socket_port=$4
ftp_log_file=$1/$2_log
#
#     Extract mission, format, and source from filename
#          ___/        /           /
#         /  _________/           /
#        /  /____________________/
#       /  //
#     WIND_FI_1997_211_00204_54051.blk_replay
#
ftp_mission=`expr "$ftp_input_file" : '\(.*\)_.._...._.*_.*_.*\..*'`
ftp_format=`expr  "$ftp_input_file" : '.*_\(.\)._...._.*_.*_.*\..*'`
ftp_source=`expr  "$ftp_input_file" : '.*_.\(.\)_...._.*_.*_.*\..*'`

# parse replayrc script
if [ -f "$replayrc" ]
then
   alt_display_list=`grep '^DISPLAY' $replayrc 2>/dev/null | tail -1`
   alt_display_list=`expr "$alt_display_list" : 'DISPLAY.*=\(.*\);'`
   alt_display_list=`echo "$alt_display_list" | tr '[,]' '[ ]'`

   alt_text_editor=`grep '^EDITOR' $replayrc 2>/dev/null | tail -1`
   alt_text_editor=`expr "$alt_text_editor" : 'EDITOR.*=\(.*\);'`
   if [ "$alt_text_editor" != "" ]
   then
      text_file_editor="$alt_text_editor"
   fi

   alt_ignore_list=`grep '^IGNORE' $replayrc 2>/dev/null | tail -1`
   alt_ignore_list=`expr "$alt_ignore_list" : 'IGNORE.*=\(.*\);'`
   alt_ignore_list=`echo "$alt_ignore_list" | tr '[a-z]' '[A-Z]' | tr '[,]' '[ ]'`

   alt_trend_list=`grep '^TREND' $replayrc 2>/dev/null | tail -1`
   alt_trend_list=`expr "$alt_trend_list" : 'TREND.*=\(.*\);'`
   alt_trend_list=`echo "$alt_trend_list" | tr '[a-z]' '[A-Z]' | tr '[,]' '[ ]'`
fi

# initialize cleanup list and trap signals for cleanup
cleanup="eval /usr/bin/cp -p $ftp_log_file $ftp_archive_dir; /usr/bin/rm -f /dev/null"
trap "echo INTERRUPT; echo `date` ABORTED >> $ftp_log_file; $cleanup; exit 6" 1 2 3 15

# log replay configuration
echo ""							>> $ftp_log_file
echo "`date` FTP REPLAY STARTED"			>> $ftp_log_file
echo ""							>> $ftp_log_file
echo "`date` FTP REPLAY PARAMETERS"			>> $ftp_log_file
echo "      interactive = $interactive"			>> $ftp_log_file
echo "        sync_only = $sync_only"			>> $ftp_log_file
echo "         replayrc = $replayrc"			>> $ftp_log_file
echo "   ftp_config_dir = $ftp_config_dir"		>> $ftp_log_file
echo "    ftp_trend_dir = $ftp_trend_dir"		>> $ftp_log_file
echo "  ftp_archive_dir = $ftp_archive_dir"		>> $ftp_log_file
echo " text_file_editor = $text_file_editor"		>> $ftp_log_file
echo "     ftp_lock_dir = $ftp_lock_dir"		>> $ftp_log_file
echo "    ftp_input_dir = $ftp_input_dir"		>> $ftp_log_file
echo "   ftp_input_file = $ftp_input_file"		>> $ftp_log_file
echo "  ftp_capture_dir = $ftp_capture_dir"		>> $ftp_log_file
echo "  ftp_socket_port = $ftp_socket_port"		>> $ftp_log_file
echo "     ftp_log_file = $ftp_log_file"		>> $ftp_log_file
echo "      ftp_mission = $ftp_mission"			>> $ftp_log_file
echo "       ftp_format = $ftp_format"			>> $ftp_log_file
echo "       ftp_source = $ftp_source"			>> $ftp_log_file
echo "      alt_display = $alt_display"			>> $ftp_log_file
echo "  alt_text_editor = $alt_text_editor"		>> $ftp_log_file
echo "  alt_ignore_list = $alt_ignore_list"		>> $ftp_log_file
echo "   alt_trend_list = $alt_trend_list"		>> $ftp_log_file


###############  IGNORE INPUT FILE?  ###############


# determine whether to ignore file
case $ftp_mission in
   WIND)    alt_ignore_list="$alt_ignore_list Z"   ;; # add Z files only
   POLAR)   alt_ignore_list="$alt_ignore_list Z G" ;; # add PWIW as well
   GEOTAIL) alt_ignore_list="$alt_ignore_list Z"   ;; # add Z files only
   *)       alt_ignore_list="$alt_ignore_list Z"   ;; # add Z files only
esac
for option in $alt_ignore_list
do
   if [ "$option" = "$ftp_format" ]
   then
      if [ "$interactive" = "true" ]
      then
         echo ""
         echo "WARNING: lzp_replay: file ignored"
         printf "Process file anyway? [N]: "
         read answer
         answer=`echo "$answer" | tr '[a-z]' '[A-Z]' | tr -cd "YN"`
         if [ "$answer" = "Y" ]
         then
            printf "Are you sure? [N]: "
            read answer
            answer=`echo "$answer" | tr '[a-z]' '[A-Z]' | tr -cd "YN"`
         fi
         if [ "$answer" = "Y" ]
         then
            # process file anyway
            echo ""					>> $ftp_log_file
            echo "`date` INPUT FILE FORCED"		>> $ftp_log_file
            break
         fi
      fi
      echo ""						>> $ftp_log_file
      echo "`date` INPUT FILE IGNORED"			>> $ftp_log_file
      echo ""						>> $ftp_log_file
      echo "`date` FTP REPLAY COMPLETED"		>> $ftp_log_file
      cleanup="$cleanup $ftp_input_dir/$ftp_input_file $ftp_log_file"
      $cleanup
      exit 5
   fi
done


###############  SET DISPLAY ADDRESS  ###############


# determine display address for user interfaces
if [ "$interactive" = "true" ]
then
   alt_display_list="$DISPLAY" # try only the current display
else
   alt_display_list="$alt_display_list $DISPLAY" # append current display
   DISPLAY=`netstat -n -I hme0 2>/dev/null| tail -1| awk '{ print $4 }'`":0.0"
   alt_display_list="$alt_display_list $DISPLAY" # append console display
fi
echo "" >> $ftp_log_file
while [ forever ]
do
   for option in $alt_display_list
   do
      DISPLAY="$option"; export DISPLAY
      echo "`date` USING DISPLAY $DISPLAY" >> $ftp_log_file

      # query display configuration
      xset q 1>/dev/null 2>/dev/null
      if [ $? = 0 ]
      then
         # found usable display
         break
      fi

      # skip unusable display
      DISPLAY=""; export DISPLAY
   done
   if [ "$interactive" = "true" -a "$DISPLAY" = "" ]
   then
      echo ""
      echo "WARNING: lzp_replay: bad display"
      printf "Enter display [$alt_display_list]: "
      read answer
      if [ "$answer" ]
      then
         alt_display_list="$answer"
      fi
   else
      # break infinite loop
      break
   fi
done
if [ "$DISPLAY" = "" ]
then
   echo "`date` BAD DISPLAY ADDRESS"					>> $ftp_log_file
   echo ""								>> $ftp_log_file
   echo "Possible causes:  The specified DISPLAY does not exist"	>> $ftp_log_file
   echo "or is not accepting connections.  If the DISPLAY is a"		>> $ftp_log_file
   echo "console, verify that xhost + has been executed and"		>> $ftp_log_file
   echo "that there is an active login session on the console."		>> $ftp_log_file
   echo "The .replayrc file in your home directory may be used"		>> $ftp_log_file
   echo "to specify alternate DISPLAY addresses if desired."		>> $ftp_log_file
   echo ""								>> $ftp_log_file
   echo "`date` FTP REPLAY FAILED"					>> $ftp_log_file
   $cleanup
   exit 8
fi


###############  FRAME SYNC PROCESSING  ###############


echo ""	>> $ftp_log_file
amf_input_file=`expr "$ftp_input_file" : '\(.*\.amf\).*'`
if [ "$amf_input_file" != "" ]
then

   # bypass frame sync processing
   fs_output_file="$ftp_input_dir/$ftp_input_file"

   # log bypass configuration
   echo ""
   echo "BYPASSING FRAME SYNCHRONIZER..."
   echo "`date` FRAME SYNCHRONIZER BYPASSED"		>> $ftp_log_file
   echo " fs_output_file = $fs_output_file"		>> $ftp_log_file

else

   # determine frame sync configuration
   fs_process_name="/opt/irts/bin/sw_sync"
   fs_baseline_file="$ftp_mission"_"$ftp_format$ftp_source.cfg"
   fs_config_file="$ftp_config_dir/Frame_Sync_Startup.$$"
   fs_input_file="$ftp_input_dir/$ftp_input_file"
   fs_output_file="$ftp_input_dir/"`expr "$ftp_input_file" : '\(.*\)\..*'`".amf_replay"
   cleanup="$cleanup $fs_config_file"
   trap "echo INTERRUPT; echo `date` ABORTED >> $ftp_log_file; $cleanup; exit 6" 1 2 3 15

   # create configuration file from baseline
   if [ -f "$ftp_config_dir/$fs_baseline_file" ]
   then
      fs_baseline_file="$ftp_config_dir/$fs_baseline_file"
      /usr/bin/cp -p "$fs_baseline_file" "$fs_config_file"
   else
      fs_baseline_file="/opt/irts/etc/$fs_baseline_file"
      /usr/bin/cp -p "$fs_baseline_file" "$fs_config_file"
   fi

   # interactive configuration
   if [ "$interactive" = "true" ]
   then
      echo ""
      echo "EDITING FRAME SYNCHRONIZER CONFIGURATION..."
      echo "`date` CONFIGURATION EDITOR STARTED"	>> $ftp_log_file
      /usr/bin/chmod 644 "$fs_config_file"
      $text_file_editor $fs_config_file 1>/dev/null 2>/dev/null
      if [ $? = 0 ]
      then
         echo "EXECUTING FRAME SYNCHRONIZER PROCESS..."
         echo "`date` CONFIGURATION EDITOR COMPLETED"	>> $ftp_log_file
      else
         echo "ERROR: lzp_replay: configuration editor"
         echo "`date` CONFIGURATION EDITOR FAILED"	>> $ftp_log_file
         echo ""					>> $ftp_log_file
         echo "date` FTP REPLAY FAILED"			>> $ftp_log_file
         $cleanup
         exit 9
      fi
   fi

   # log frame sync configuration
   echo "`date` FRAME SYNCHRONIZER STARTED"		>> $ftp_log_file
   echo ""						>> $ftp_log_file
   echo "`date` FRAME SYNCHRONIZER PARAMETERS"		>> $ftp_log_file
   echo " fs_process_name = $fs_process_name"		>> $ftp_log_file
   echo "fs_baseline_file = $fs_baseline_file"		>> $ftp_log_file
   echo "  fs_config_file = $fs_config_file"		>> $ftp_log_file
   echo "   fs_input_file = $fs_input_file"		>> $ftp_log_file
   echo "  fs_output_file = $fs_output_file"		>> $ftp_log_file
   echo ""						>> $ftp_log_file
   echo "`date` FRAME SYNCHRONIZER CONFIG FILE"		>> $ftp_log_file
   /usr/bin/cat "$fs_config_file"			>> $ftp_log_file
   echo ""						>> $ftp_log_file
   echo "`date` FRAME SYNCHRONIZER OUTPUT"		>> $ftp_log_file

   # invoke frame sync process
   cleanup="$cleanup $fs_output_file"
   trap "echo INTERRUPT; echo `date` ABORTED >> $ftp_log_file; $cleanup; exit 6" 1 2 3 15
   $fs_process_name $fs_config_file $fs_input_file $fs_output_file 1>>$ftp_log_file 2>>$ftp_log_file
   if [ $? = 0 ]
   then
      # frame sync completed
      /usr/bin/rm -f "$fs_config_file"
      /usr/bin/chmod 644 "$fs_output_file"
      echo "`date` FRAME SYNCHRONIZER COMPLETED"	>> $ftp_log_file
   else
      # frame sync failed
      echo "ERROR: lzp_replay: frame synchronizer"
      echo "`date` FRAME SYNCHRONIZER FAILED"		>> $ftp_log_file
      echo ""						>> $ftp_log_file
      echo "`date` FTP REPLAY FAILED"			>> $ftp_log_file
      $cleanup
      exit 2
   fi
fi


###############  STOP AFTER SYNC?  ###############


if [ "$interactive" = "true" -a "$amf_input_file" = "" ]
then
   echo ""
   echo "Files generated by the frame synchronization process"
   echo "may be placed on hold for manual analysis and editing."
   echo "The following file may be held for manual processing:"
   echo ""
   echo "$fs_output_file"
   printf "Hold for analysis? [N]: "
   read answer
   answer=`echo "$answer" | tr '[a-z]' '[A-Z]' | tr -cd "YN"`
   if [ "$answer" = "Y" ]
   then
      printf "Are you sure? [N]: "
      read answer
      answer=`echo "$answer" | tr '[a-z]' '[A-Z]' | tr -cd "YN"`
   fi
   sync_only=false
   if [ "$answer" = "Y" ]
   then
      echo ""
      echo "AMF FILE PLACED ON HOLD"
      sync_only=true
   fi
fi

if [ "$sync_only" = "true" ]
then
   echo "`date` AMF FILE PLACED ON HOLD"		>> $ftp_log_file
   echo ""						>> $ftp_log_file
   echo "`date` FTP REPLAY COMPLETED"			>> $ftp_log_file
   /usr/bin/mv -f $fs_output_file $fs_output_file"_hold"
   $cleanup
   exit 0
fi


###############  TREND FILE TRANSFER  ###############


# determine trend transfer parameters
tr_process_name="lzp_trend"
tr_input_file="$fs_output_file"
tr_output_file=`expr "$fs_output_file" : '.*/\(.*\)\..*'`".amf"
tr_output_dir="$ftp_trend_dir"
tr_forward_flag=false

# determine whether to attempt trend transfer
if [ ! "$alt_trend_list" ]
then
   case $ftp_mission in
      WIND)    alt_trend_list="A B C D E F" ;;
      POLAR)   alt_trend_list="C D" ;;
      GEOTAIL) alt_trend_list="" ;;
      *)       alt_trend_list="" ;;
   esac
fi
for option in $alt_trend_list
do
   if [ "$option" = "$ftp_format" ]
   then
      tr_forward_flag=true
      break
   fi
done

# interactive transfer query
if [ "$interactive" = "true" ]
then
   echo ""
   if [ "$tr_forward_flag" = "true" ]
   then
      echo "Files are NOT typically forwarded for trending during"
      echo "interactive data processing, however the software is"
      echo "currently configured to forward the following file:"
   else
      echo "Files are NOT typically forwarded for trending during"
      echo "interactive data processing, NEITHER is the software"
      echo "currently configured to forward the following file:"
   fi
   echo ""
   echo "$tr_output_file"
   printf "Forward file anyway? [N]: "
   read answer
   answer=`echo "$answer" | tr '[a-z]' '[A-Z]' | tr -cd "YN"`
   if [ "$answer" = "Y" ]
   then
      printf "Are you sure? [N]: "
      read answer
      answer=`echo "$answer" | tr '[a-z]' '[A-Z]' | tr -cd "YN"`
   fi
   tr_forward_flag=false
   if [ "$answer" = "Y" ]
   then
      echo ""
      echo "EXECUTING TREND TRANSFER PROCESS..."
      tr_forward_flag=true
   fi
fi

# attempt trend transfer when appropriate
if [ "$tr_forward_flag" = "true" ]
then
   # log trend transfer parameters
   echo ""						>> $ftp_log_file
   echo "`date` TREND TRANSFER STARTED"			>> $ftp_log_file
   echo ""						>> $ftp_log_file
   echo "`date` TREND TRANSFER PARAMETERS"		>> $ftp_log_file
   echo "  tr_process_name = $tr_process_name"		>> $ftp_log_file
   echo "   alt_trend_list = $alt_trend_list"		>> $ftp_log_file
   echo "    tr_input_file = $tr_input_file"		>> $ftp_log_file
   echo "   tr_output_file = $tr_output_file"		>> $ftp_log_file
   echo "    tr_output_dir = $tr_output_dir"		>> $ftp_log_file
   echo ""						>> $ftp_log_file

   trap "" 1 2 3 15

   # invoke trend transfer process
   /usr/bin/cp -p $tr_input_file $tr_output_dir/.$tr_output_file 2>/dev/null
   if [ $? = 0 ]
   then
      /usr/bin/at -s -q b -m now << BATCH_ARGS_EOF
      $tr_process_name -rv $tr_output_dir/.$tr_output_file
BATCH_ARGS_EOF
      echo "`date` TREND TRANSFER COMPLETED"		>> $ftp_log_file
   else
      echo "`date` TREND TRANSFER FAILED"		>> $ftp_log_file
   fi

   trap "echo INTERRUPT; echo `date` ABORTED >> $ftp_log_file; $cleanup; exit 6" 1 2 3 15
fi


###############  ASSEMBLY DECOM PROCESSING  ###############


# determine packetizer configuration
pk_process_name="ad"
pk_config_file="$ftp_config_dir/Assembly_Decom_Startup.$$"
pk_lock_file="$ftp_lock_dir/Assembly_Decom_Startup.parm"
pk_input_file="$fs_output_file"
pk_output_file="$ftp_socket_port"
cleanup="$cleanup $pk_config_file"
trap "echo INTERRUPT; echo `date` ABORTED >> $ftp_log_file; $cleanup; exit 6" 1 2 3 15

# default AD configuration
pk_Run_When_Opened="ON"
pk_Master_Dialog_Switch="OFF"
pk_Input_Origin="$ftp_input_file"
pk_Assembly_Decom_Input_amf="$pk_input_file"
pk_Session_Archive_Path="$ftp_capture_dir"
pk_FTP_Replay_Log="$ftp_log_file"

# default DPS configuration
pk_Write_To_DPS_Switch="ON"
pk_DPS_Port_Number="$ftp_socket_port"

# default RECON configuration
pk_Reconstruction_Switch="ON"
pk_Quicklook_Switch="ON"
pk_Multiple_Quicklook_Switch="OFF"

# default MISC configuration
pk_Order_By_GRT_Switch="OFF"
pk_Force_RS_Error_Switch="OFF"
pk_Major_Frame_Dump_Switch="OFF"
pk_Mission_Name="$ftp_mission"
pk_PDF_Name="PDF$ftp_format"

# mission specific configuration for WIND
if [ "$ftp_mission" = "WIND" ]
then
   case $ftp_format in
      D) pk_Force_RS_Error_Switch="ON" ;;
      E) pk_Force_RS_Error_Switch="ON" ;;
      F) pk_Force_RS_Error_Switch="ON" ;;
   esac
fi

# mission specific configuration for POLAR
if [ "$ftp_mission" = "POLAR" ]
then
   case $ftp_format in
      # C) pk_Force_RS_Error_Switch="ON" ;;
      # D) pk_Force_RS_Error_Switch="ON" ;;
      G) pk_Mission_Name="PWIW"; pk_Order_By_GRT_Switch="ON" ;;
   esac
fi

# mission specific configuration for GEOTAIL
if [ "$ftp_mission" = "GEOTAIL" ]
then
   case $ftp_format in
      # C) pk_Force_RS_Error_Switch="ON" ;;
      # D) pk_Force_RS_Error_Switch="ON" ;;
   esac
fi

# default interactive configuration
if [ "$interactive" = "true" ]
then
   pk_Major_Frame_Dump_Switch="RECON"
fi

# create configuration file
/usr/bin/cat << PK_CONFIG_EOF > "$pk_config_file"
SECTION = ASSEMBLY DECOM;
Run_When_Opened = $pk_Run_When_Opened;
Master_Dialog_Switch = $pk_Master_Dialog_Switch;
Input_Origin = $pk_Input_Origin;
Assembly_Decom_Input_amf = $pk_Assembly_Decom_Input_amf;
Session_Archive_Path = $pk_Session_Archive_Path;
FTP_Replay_Log = $pk_FTP_Replay_Log;

SECTION = DATA PROCESSING SYSTEM;
Write_To_DPS_Switch = $pk_Write_To_DPS_Switch;
DPS_Port_Number = $pk_DPS_Port_Number;

SECTION = ORACLE RECONSTRUCTION;
Reconstruction_Switch = $pk_Reconstruction_Switch;
Quicklook_Switch = $pk_Quicklook_Switch;
Multiple_Quicklook_Switch = $pk_Multiple_Quicklook_Switch;

SECTION = MISCELLANEOUS PARAMETERS;
Order_By_GRT_Switch = $pk_Order_By_GRT_Switch;
Force_RS_Error_Switch = $pk_Force_RS_Error_Switch;
Major_Frame_Dump_Switch = $pk_Major_Frame_Dump_Switch;
Mission_Name = $pk_Mission_Name;
PDF_Name = $pk_PDF_Name;

SECTION = REPLAYRC PARAMETERS;
PK_CONFIG_EOF

# append replayrc file
echo "" >> $ftp_log_file
if [ -f "$replayrc" ]
then
   /usr/bin/cat "$replayrc" >> "$pk_config_file"
fi

# interactive configuration
if [ "$interactive" = "true" ]
then
   echo ""
   echo "EDITING PACKETIZER CONFIGURATION..."
   echo "`date` CONFIGURATION EDITOR STARTED"		>> $ftp_log_file
   /usr/bin/chmod 644 "$pk_config_file"
   $text_file_editor $pk_config_file 1>/dev/null 2>/dev/null
   if [ $? = 0 ]
   then
      echo "EXECUTING PACKETIZER PROCESS..."
      echo ""
      echo "`date` CONFIGURATION EDITOR COMPLETED"	>> $ftp_log_file
   else
      echo "ERROR: lzp_replay: configuration editor"
      echo "`date` CONFIGURATION EDITOR FAILED"		>> $ftp_log_file
      echo ""						>> $ftp_log_file
      echo "`date` FTP REPLAY FAILED"			>> $ftp_log_file
      $cleanup
      exit 9
   fi
fi

# log packetizer configuration 
echo "`date` PACKETIZER STARTED"			>> $ftp_log_file
echo ""							>> $ftp_log_file
echo "`date` PACKETIZER PARAMETERS"			>> $ftp_log_file
echo "pk_process_name = $pk_process_name"		>> $ftp_log_file
echo "   pk_lock_file = $pk_lock_file"			>> $ftp_log_file
echo " pk_config_file = $pk_config_file"		>> $ftp_log_file
echo "  pk_input_file = $pk_input_file"			>> $ftp_log_file
echo " pk_output_file = $pk_output_file"		>> $ftp_log_file
echo ""							>> $ftp_log_file
echo "`date` PACKETIZER CONFIGURATION FILE"		>> $ftp_log_file
/usr/bin/cat "$pk_config_file"				>> $ftp_log_file
echo ""							>> $ftp_log_file

# grab semaphore
wait_time=0
while [ forever ]
do
   echo "Waiting for semaphore..."
   if [ `expr $wait_time % $wait_log` = 0 ]
   then
      echo "`date` SEMAPHORE WAIT"			>> $ftp_log_file
   fi
   trap "" 1 2 3 15
   /usr/bin/ln -s $pk_config_file $pk_lock_file
   if [ $? = 0 ]
   then
      cleanup="$cleanup $pk_lock_file"
      trap "echo INTERRUPT; echo `date` ABORTED >> $ftp_log_file; $cleanup; exit 6" 1 2 3 15
      echo "Obtained semaphore; no error"
      echo "`date` SEMAPHORE OBTAINED"			>> $ftp_log_file
      echo ""						>> $ftp_log_file
      break
   fi
   echo ""
   trap "echo INTERRUPT; echo `date` ABORTED >> $ftp_log_file; $cleanup; exit 6" 1 2 3 15
   sleep $wait_sleep
   wait_time=`expr $wait_time + $wait_sleep`
   if [ $wait_time -gt $wait_timeout ]
   then
      echo "ERROR: lzp_replay: semaphore timeout"
      echo "`date` SEMAPHORE TIMEOUT"			>> $ftp_log_file
      echo ""						>> $ftp_log_file
      echo "`date` FTP REPLAY FAILED"			>> $ftp_log_file
      $cleanup
      exit 7
   fi
done

# invoke packetizer process
/usr/bin/rm -f $HOME/stat/*POSTINGERROR.msg 1>/dev/null 2>/dev/null
$pk_process_name 1>>$ftp_log_file 2>>$ftp_log_file
/usr/bin/rm -f "$pk_config_file"

# log packetizer status
pk_success_message="Event 2000"
pk_status=`tail -10 $ftp_log_file 2>/dev/null | grep -cs "$pk_success_message"`
if [ "$pk_status" = 1 ]
then
   # packetizer completed
   echo "`date` PACKETIZER COMPLETED"			>> $ftp_log_file
   echo ""						>> $ftp_log_file
else
   # packetizer failed
   echo "ERROR: lzp_replay: packetizer"
   echo "`date` PACKETIZER FAILED"			>> $ftp_log_file
   echo ""						>> $ftp_log_file
   echo "`date` FTP REPLAY FAILED"			>> $ftp_log_file
   $cleanup
   exit 3
fi

# replay completed
echo "`date` FTP REPLAY COMPLETED"			>> $ftp_log_file
$cleanup
echo "SUCCESS: lzp_replay: completed"
exit 0
