#!/bin/bash
#####################################################################
# 
# rt_check.bash 
#
# Purpose:
# This shell script performs cleanup of intermediate processing data
# and verifies the successful generation of real-time product outputs.
#
# History:  
#       Created by: Ming Chen 2026/06/03
#                   ming.chen@noaa.gov
# 
# Usage: rt_check.bash 
# 
#
#####################################################################
#

pkghome=/home/mchen36/wrk/RT_COSMIC2_REL1.2
cd ${pkghome}
source set_env.bash

if [ -z "${podgen_home}" ]; then 
   echo "env is not set up, source the set_env.bash file first .."
   exit
fi

podgen=${podgen_home}
pdate=$(date -u  '+%Y%m%d %H%M')
if [ -n "$1" ]; then
  pdate="$1"
fi

cdate=$(date -d "$pdate -1 day" +"%Y%m%d %H%M" )
mission=cosmic2
umd=${data_home}/umd/${mission}
podprod=${data_home}/${mission}/LEOPOD
cdatestr=`date -d "$cdate" +"%Y.%j"`
pdatestr=`date -d "$pdate" +"%Y.%j"`
ptime=`date -d "$pdate" +"%H%M"`

podRnx=${umd}/podRnx/${cdatestr}
leoAtt=${umd}/podRnx/${cdatestr}
leoorb=${podprod}/leoOrb/${pdatestr}
#echo ${leoorb}
if [ -d ${podRnx} ]; then rm -fr ${podRnx} ; fi
if [ -d ${leoAtt} ]; then rm -fr ${leoAtt} ; fi
flatest=`ls  -t ${leoorb}/*.SP3 2>/dev/null |  head -n 1 | tr -d '\r' | tr -d '[:space:]'`
if [[ "${ptime}" < '0030' ]] && [ -z  "${flatest}" ]; then
   leoorb=${podprod}/leoOrb/${cdatestr}
   flatest=`ls  -t ${leoorb}/*.SP3 2>/dev/null |  head -n 1 | tr -d '\r' | tr -d '[:space:]'`
fi	
if [  -n "${flatest}" ]; then
   ftime=`echo ${flatest##*/} | cut -d'_' -f2 | sed 's/T/ /'`
   #echo "ftime ${ftime%??}"
   #echo "pdate $pdate "
   s1=`date -d "${ftime%??}" +%s`
   s2=`date -d "${pdate}" +%s`
   df="$(( s2 - s1 ))"
   if [ $df -gt 3600 ]; then
      msg="Alert: COSMIC2 RT processing may have some issue ..."
      #aws sns publish \
      #  --topic-arn "arn:aws:sns:us-east-1:190556942226:gitLab-ssbox-gnssro" \
      #  --message "$msg"
      echo "$msg" | mail -s "COSMIC2 RT processing alert" ming.chen@noaa.gov
     
   fi
else
   msg="Alert: COSMIC2 RT processing has stopped"
   #aws sns publish \
   #     --topic-arn "arn:aws:sns:us-east-1:190556942226:gitLab-ssbox-gnssro" \
   #     --message "$msg"
   echo "$msg" | mail -s "COSMIC2 RT processing alert" ming.chen@noaa.gov
fi
