#!/bin/bash
#  Version: 01/28/05
#  Utility script to launch the data assimilation for a previously
#  partitioned and copied set of input files.  We launch the assimilation
#  and place back the results to the destination directories when finished.
#  We also delete the input grid files.
#  The command-line arguments to this script are compatible with assim_p.
#
#  Variables in UPPER CASE are command-line arguments.  Those in lower case
#  are internal to the script.

#  Defaults
version="03/29/05"
EXEDIR=
EGRID=egrid   # base name of input model grid file; deleted on successful exit
YOBS=yobs     # base name of observation grid file; deleted on successful exit
NATGRID=""    # base name of "true" model grid data; deleted on successful exit
EGRID_OUT=egrid.out  # base name of analysis output grid file
DIAG=""       # base name of diagnostics file; appended to existing file, if any
LOG=log       # log file; ditto
ERRLOG=errlog # error log file; ditto
OBSTYPE="PTUV"  # observation variable types to assimilate
OBS_TEMP_UNIT='K' # temperature observations in Kelvin
OBSCHECK="none" # no internal obs consistency checks by default

#  Data assimilation parameters
NODE=$(hostname -a) #name of node on which to run; default: current node
XWIDTH=3     #longitude radius of grid patch
YWIDTH=3     #latitude radius of grid patch
ZRAD=""      #vertical localization radii file, if any
NSOL=40     #number of ensemble solutions
VERBLEV=1    #save brief log files from assimilation step
SEQID=0      #sequence id - helps keep egrid/yobs/analysis files consistent
INDFILE=     #index file for extra diagnostics
ERRTHRESH=0  #max allowed fraction of patches with assimilation errors
RESULTDIR=.  #destination directory for output files

#set -x
#  Use a default scratch subdirectory with the user's name, if available
#
function usage {
    echo "Usage: run_assim_p [options]"
    echo "Version: $version"
    echo "Options:"
    echo "-h (to print this message)"
    echo "-A observation_typelist (current: $OBSTYPE)"
    echo "-a analysis_file (current name: $EGRID_OUT)"
    echo "-b background_grid_file (current name: $EGRID)"
    echo "-c data_consistency_checktype (none, whitaker, observation)"
    echo "-d diag_output_file (default: none)"
    echo "-e error_log_basename (current: $ERRLOG)"
    echo "-E assim_error_fraction (current: $ERRTHRESH)"
    echo "-L log_basename (current: $LOG)"
    echo "-n number_of_ensemble_solutions (current: $NSOL)"
    echo "-N remote_node_name (current: $NODE)"
    echo "-o observation_file (current name: $YOBS)"
    echo "-P execute_path_directory (current: $EXEDIR)"
    echo "-q sequence_id (current: $SEQID)"
    echo "-r resultdir (current: $RESULTDIR)"
    echo "-t nature_grid_filename (default: none)"
    echo "-v verbosity_level (0:silent 1:terse 2:show progress 3:chatty)"
    echo "-w scratch_directory (current: $SCRATCH)"
    echo "-x longitudinal radius of grid patch (current: $XWIDTH)"
    echo "-y latitudinal radius of grid patch (current: $YWIDTH)"
    echo "   each patch is a (2x+1)*(2y+1) rectangle of grid points"
    echo "-z vertical localization radii file (current: $ZRAD)"
    exit 1
}

while getopts a:A:b:c:d:e:E:hL:n:N:o:P:q:r:T:t:v:x:y:z: opt
do
    case $opt in
    A)  OBSTYPE=$OPTARG;;
    a)  EGRID_OUT=$OPTARG;;
    b)  EGRID=$OPTARG;;
    c)  OBSCHECK=$OPTARG;;
    d)  DIAG=$OPTARG;;
    e)  ERRLOG=$OPTARG;;
    E)  ERRTHRESH=$OPTARG;;
    h)  usage;;
    L)  LOG=$OPTARG;;
    n)  NSOL=$OPTARG;;
    N)  NODE=$OPTARG;;
    o)  YOBS=$OPTARG;;
    P)  EXEDIR=$OPTARG;;
    q)  SEQID=$OPTARG;;
    r)  RESULTDIR=$OPTARG;;
    T)  OBS_TEMP_UNIT=$OPTARG;;
    t)  NATGRID=$OPTARG;;
    v)  VERBLEV=$OPTARG;;
    x)  XWIDTH=$OPTARG;;
    y)  YWIDTH=$OPTARG;;
    z)  ZRAD=$OPTARG;;
    \?) usage ;;
    esac
done

#echo "$0: version $version: start" 1>&2 # debug

#  Initialize 
if [ ! -n "$EXEDIR" ]
then
   export PATH=${EXEDIR}:$PATH
fi
mach=$NODE
host=$(hostname -a)

# launch the assimilation and track the exit code

options="-b $EGRID -o $YOBS -a $EGRID_OUT -q $SEQID"
options="$options -n $NSOL -x $XWIDTH -y $YWIDTH -T $OBS_TEMP_UNIT -A $OBSTYPE"
options="$options -v $VERBLEV -e $ERRTHRESH"

if [ -n "$NATGRID" ]
then
   options="$options -t $NATGRID"
fi
if [ -n "$DIAG" ]
then
   options="$options -d $DIAG"
fi
if [ -n "$ZRAD" ]
then
   options="$options -z $ZRAD"
fi
if [ -n "$OBSCHECK" ]
then
   options="$options -c $OBSCHECK"
fi

#  full path name of assim_p is needed on remote nodes, as rsh may
#  not source .profile

if [ $mach != $host ]  # run remotely
then
   errcode=$(rsh $mach "(export LD_LIBRARY_PATH=$LD_LIBRARY_PATH; \
      $EXEDIR/assim_p $options 2>$ERRLOG >$LOG || echo \$?)")
else  # run locally
    $EXEDIR/assim_p $options 2>$ERRLOG >$LOG
    errcode=$?
    if [ $errcode -eq 0 ]
    then
       errcode="" # so we agree with the rsh convention above: silence=success
    fi
fi

#  If there's an error leave the inputs and temporaries for a postmortem
if [ -n "$errcode" ]
then
   echo $0: error code $errcode in analysis on $mach 1>&2
   exit $errcode
fi

rm -f $EGRID $YOBS $NATGRID
exit 0
