#!/bin/bash
#
# To cron Aqua and Terra passes we have to know the maximum timeliness
# Aqua and Terra have DOY in filename, I found jul() on stackabuse.com
# Bash function jul() { date -d "$1-01-01 $2 days -1 day" "+%Y%m%d"; }
# Oase, 2022/12/06                                         E. Lobsiger
#

jus() { date -d "$1-01-01 $2 days -1 day +$3 hours +$4 minutes " "+%s"; }

# File Pattern : thin_M{platform_indicator:1s}D021KM.A{start_time:%Y%j.%H%M}.{collection:03d}{suffix}.hdf
# Example name : thin_MOD021KM.A2019083.1300.061.NRT.hdf
# Hugo's ruler : 012345678901234567890123456789012345678
# copied EMCV  : 0         1         2         3

maxt=0
mint=100000
minp=0
maxp=250
sat="EOS-Terra"
chann="E1B-TPL-1"
color="brown"
here=`pwd`
dat1=`date -u -d "-5 days" +%Y/%m/%d`
dat2=`date -u -d "-1 days" +%Y/%m/%d`
rm -f $here/timeliness.txt
# On BASIC Service channel E1B-TPL-1
for n in -5 -4 -3 -2 -1
do
    thisday=`date -u -d "$n days" +%Y/%m/%d`
    cd "/srv/$chann/$thisday"

    # This is for satellite EOS-Terra
    for name in `ls -rt thin_MOD*.hdf`
    do
        yea=${name:15:4}
        doy=${name:19:3}
        hou=${name:23:2}
        min=${name:25:2}
        start=` jus $yea $doy $hou $min`
        trans=`stat -c "%Y" $name`
        # You should run your receiver/processor under UTC!
        # trans=`date -u -d "1970-01-01 $trans seconds" "+%s"`
        timeliness=$(((trans - start)/60))
        if (( timeliness > maxt )); then maxt=$timeliness; fi
        if (( timeliness < mint )); then mint=$timeliness; fi
        echo $timeliness >> $here/timeliness.txt
    done
done
cd $here
gnuplot -e "sat='$sat'; dat1='$dat1'; dat2='$dat2'; mint=$mint; maxt=$maxt;\
            minp=$minp; maxp=$maxp; chann='$chann'; color='$color'" LEO-SATS.plt
