#!/bin/bash
#
# To cron Himawari-8 (HIMA8) we look for the timeliness of all files first
# This satellite produces a hell of a bunch of files. Please be patient ..
# Oase, 2022/12/06                                             E. Lobsiger

# Typical naming of Himawari-8 channel data files (channel B01, segment 4)
# File pattern : IMG_DK{area:02d}B01_{start_time:%Y%m%d%H%M}_{segment:03d}
# Example name : IMG_DK01B01_202204071252_004.bz2
# Hugo's ruler : 01234567890123456789012345678901234567890
# copied EMCV  : 0         1         2         3         4
# EUMETCast    : These files arrive as above in channel E1H-TPG-2 (HVS-1)

mint=100000
maxt=0
maxp=35
minp=0
sat="Himawari-8"
chann="E1H-TPG-2"
color="turquoise"
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 HVS-1 Service Channel E1H-TPG-2
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 HIMA8
    for name in `ls -rt IMG_DK*.bz2`
    do
        yea=${name:12:4}
        mon=${name:16:2}
        day=${name:18:2}
        hou=${name:20:2}
        min=${name:22:2}
        start=`date -d "$yea-$mon-$day $hou:$min" "+%s" `
        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'" GEO-TPGX.plt
