#!/bin/bash
# A general BERN54 command-line driver script
# for real-time COSMIC-2 processing
#####################################################################
# 
# rt_cosmic2_bern.bach
#
# Purpose:
# This shell script runs the COSMIC-2 BERNESE processing
# and associated post-processing scripts.
#
# History:  
#       Created by: Ming Chen 2026/04/21
#                   ming.chen@noaa.gov
# 
# Usage: rt_cosmic2_bern.bach  Args
#
# Args:  {satidx} {antidx} "{timestr[yyyymnddThhmm}" "{podgen_home}
#
#####################################################################

pkg_home=$(pwd)
if [ -n $4 ]; then pkg_home="$4" ; fi
source ${podgen_home}/set_env.bash

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

pkg_home=${podgen_home}

sat="$1" ; ant="$2"

# note  double quotes \" doesn't work  for bash date -d
# remove T in the string, "T" has different meaning in Linux date  
stime=${3//\"/}
stime="${stime//T/ }"

# sdate is the end_time 
window_minutes="-720"
sdate=`date -d "$stime" +"%Y%m%d %H%M"`

t1=`date -d "$sdate " +"%Y%m%d 0000"`
t2=`date -d "$sdate  " +"%Y%m%d %H%M"`
h=`date -d "$sdate  " +"%H"`

if [[ "${h}" < "03" ]]; then
   t1=`date -d "$t2 ${window_minutes} minutes" +"%Y%m%d 0600"`
fi  
echo "$t1 $t2"
cd ${pkg_home}
echo "${pkg_home}/RunBern54/s06_run_bernese_rt.bash -m rtm -t daily -i 20 --satsys=GRE --gnssar=GRE cosmic2 $sat $ant ${t1} ${t2}" 
${pkg_home}/RunBern54/s06_run_bernese_rt.bash -m rtm -t daily -i 20 --satsys=GRE --gnssar=GRE cosmic2 $sat $ant "${t1}" "${t2}" 


sliding_interval="60"
t1=`date -d "$t2 -${sliding_interval} minutes" +"%Y%m%d %H%M"`
echo "${pkg_home}/PostProc/s09_archive_rt_pod.bash -m rtm cosmic2 $sat $ant ${t1} ${t2} "
${pkg_home}/PostProc/s09_archive_rt_pod.bash -m rtm cosmic2 $sat $ant "${t1}" "${t2}"
