#! /bin/ksh

# This script is called by the tracker every forecast hour.  It
# updates delivery locations in real-time while the tracker runs.

# This script should only ever be called directly or indirectly from
# hwrf_realtime_tracker.sh.  Calling it from anywhere else is an
# error and will have undefined consequences.

set -x

hrprocessed="$1"

function tempify {
    echo $( dirname "$1" )temp.$( basename "$1" )."$2"
}

function fail {
    exitmsg="$1"

    set +x
    echo " "
    echo "!!! ERROR in hwrf_realtime_tracker.sh:"
    for line in "$@" ; do
        echo "!!! $line"
    done
    if [[ ! -z "${PDY:-}" && ! -z "${CYL:-}" ]] ; then
        echo "!!! model= ${atcfout:-hwrf}, forecast initial time = $PDY$CYL"
    fi
    echo " "
    set -x

    "${utilscript:-${NWPROD}/util/ush}/setup.sh"
    ./err_exit "$exitmsg"
    exit 1
}

junktext=$$.$( hostname ).$RANDOM

for mid in all atcf radii atcfunix atcf_gen atcf_sink \
    atcf_hfip cps_parms structure fractwind pdfwind ike \
    genvitals
do
    trakfile="$TRAK_PREFIX$mid$TRAK_SUFFIX"
    partfile="$PART_PREFIX$mid$PART_SUFFIX"
    tempy=$( tempify "$partfile" "$junktext" )
    if [[ -s "$trakfile" ]] ; then
        cp -pf $trakfile $tempy
        mv -f $tempy "$partfile"
        rm -f $tempy # just in case mv fails
    elif [[ -e "$trakfile" ]] ; then
        # file exists but is empty
        true > "$partfile"
    fi
done

atcfunix="${PART_PREFIX}atcfunix${PART_SUFFIX}"

if [[ ! -z "$hrprocessed" && "$hrprocessed" -ge 0 ]] ; then
    # The tracker is telling us the last hour it processed
    lasthour="$hrprocessed"
else
    # The tracker did not tell us the last hour it processed, so guess it instead.
    lasthour=$( tail -1 "$atcfunix" | cut -c31-33 | awk '{ print $1 + 0 }' )
    lasthour="${lasthour:-0}"
fi

if [[ "$lasthour" -ge 12 && ! -z "$TRACK_12HR" && ! -s "$TRACK_12HR" ]] ; then
    # Copy the 12hr track only once.
    tempy=$( tempify "$atcfunix" "$junktext.12hr" )
    $USHhwrf/hwrf_cleanup_track.sh -maxhr 12 "$atcfunix" "$tempy"
    mv -f "$tempy" "$TRACK_12HR"
fi

if [[ -s "$atcfunix" && ! -z "$TRACK_PART" ]] ; then
    # Copy the full track every time the tracker is run.
    tempy=$( tempify "$atcfunix" "$junktext" )
    $USHhwrf/hwrf_cleanup_track.sh "$atcfunix" "$tempy"
    mv -f "$tempy" "$TRACK_PART"
fi
