#!/bin/bash
# BERN54 command-line driver script
#####################################################################
# 
# s06_run_bernese.bach
#
# Purpose:
# This shell script is used to run the BERNESE from the command line.
#
# History:  
#       Created by: Ming Chen 2023/04/03
#                   ming.chen@noaa.gov
# 
# Usage: s06_run_bernese.bach  Args
#
# Options:  -m ,--codcom [cod|com]  [default cod if not specified]
# Options:  -t ,--session [daily|hourly] [default daily]
# Options:  -i ,--igs_frame [14|20] [default 14]
#
# Args:  mission[cosmic2|cosmic1|spire] satidx[1-6] antidx[1-2]
#        start-date[yyyyddd|yyyymndd] [end-date] 
#
#####################################################################

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

usage="Usage: $0  -m [cod|com] -t [daily|hourly] -i [14|20] mission[cosmic2|cosmic1] satidx antidx  starting-time(yyyymndd HHMM) [ending-time]"

PARSED_ARGUMENTS=$(getopt -o m:t:i:d: --long satsys: --long gnssar: -- "$@")
VALID_ARGUMENTS=$?
if [ "$VALID_ARGUMENTS" != "0" ]; then
  echo -e "$usage" ; exit 2
fi
eval set -- "$PARSED_ARGUMENTS"
 
codmgex='cod'; session='daily' ; igs_frame=14 ; debug=0
satsys='G' ; gnssar='G'
while :
do
  case "$1" in
    -m ) codmgex="$2" ; shift 2 ;;
    -t ) session="$2" ; shift 2 ;;
    -i ) igs_frame="$2" ; shift 2 ;;
    -d ) debug="$2" ; shift 2 ;;
    --satsys ) satsys="$2" ; shift 2 ;;
    --gnssar ) gnssar="$2" ; shift 2 ;;
    --) shift; break ;;
    *) echo "Unexpected option: $1 "
       echo "$usage" ; exit 2 ;;
  esac
done
igs=${igs_frame} ; igs_frame=I$igs
if [ "${codmgex^^}" == "COM" ]; then igs_frame=M${igs}; fi
V_MEANPL="IERS2010_v1.2.0"; V_SUBMOD="DESAI2016"
V_NUTMOD="IAU2000R06" ; V_PCV=${igs_frame}
if [ "${igs}" == "20" -a "${codmgex^^}" != "COM" ]; then 
  V_MEANPL="IERS2010_v1.2.0"; V_SUBMOD="DESAI2016"
  V_NUTMOD="IAU2000R06" 
fi

echo "$codmgex $session ${igs_frame}"


args=("$@")
if [ ${#args[@]} -lt 4 ]; then echo -e "$usage" ; exit 2; fi

# mission and leo satellite parameters
mission="${args[0]}" ; satidx="${args[1]}" ; antidx="${args[2]}"  
echo "Mission: $mission, Satellite Index: $satidx, Antenna Index: $antidx"
satinfo=( $(sat_ant_info $mission $satidx $antidx) )
if [ "$?" -ne 0 ]; then 
   echo -e "${satinfo[@]}"
   exit 2 
fi
echo "satinfo ${satinfo[@]}"
satsvn=${satinfo[0]} ; satname=${satinfo[1]} ; antsvn=${satinfo[2]}
bern_antid=${satinfo[3]}; campaign=${bern_antid^^}
bern_mis=${satinfo[4]}; leonum=${satinfo[5]}
echo "SatelliteSVN:$satsvn  SatelliteName:$satname  AntennaSVN:$antsvn "
echo "AntennaID in UMD_LEO: $bern_antid "
echo "Campaign:$campaign  "
echo "Mission ID:$bern_mis "
echo "LEONUM:$leonum "

# starting and ending dates
stime="${args[3]}" ; etime="${args[4]:-$stime}"
HM=`date -d "$etime" +%H%M` 

sdate=`date -d "$stime" +%Y%m%d` ; edate=`date -d "$etime" +%Y%m%d`
echo "$sdate $edate"
stime=`date -d "$stime" +%Y%m%dT%H:%M:%S` ; etime=`date -d "$etime" +%Y%m%dT%H:%M:%S`
echo "starting-date: $sdate, ending-date: $edate"

#short variable names
sat=$satname ; ant=$antsvn ; bernid=$bern_antid
echo "bernid $bernid"
# BERN env
#export HOME=${BERN_HOME}
#echo "source $HOME/.bashrc"
#source $HOME/.bashrc
echo "source $HOME/LOADGPS.setvar"
#source $HOME/BERN54/LOADGPS.setvar
source $HOME/LOADGPS.setvar
echo $U
echo $C
if [ ! -d ${P} ]; then exit 2 ; fi

podgen=${podgen_home}
bern_inp=$podgen/RunBern54/bns_inps
echo "Local Bernese manu-run inputs: " $bern_inp


#LEO data file info in the PCF
rnxdir='${D}'/${mission^^}/RINEX ; rnx=$sat'$S+0.$YO_'${HM}'_A'${antsvn}
attdir='${D}'/${mission^^}/ATTIT ; att=$sat'$YSS+0_'${HM}'.ATT'

vstainf=${mission^^}_LEO ; vsatinf=SATELLIT_${bern_mis}${antsvn} 
#vstainf=${mission^^}_LEO ; vsatinf=SATELLIT 
# leonum, parameter used internally by BERNESE
leonum=${leonum:-922}

V_ORBDIR='${D}/COD' ; V_ORB='COD' ; V_SATSYS='G' ; V_GNSSAR='G'
V_SAMPL='30'
V_SAV='N' ; V_SAVOBS='N'

if [ "${codmgex^^}" == "COM" ]; then 
  V_ORBDIR='${D}/COD0MGXFIN'; V_ORB="COM"
  V_SATSYS="$satsys" ; V_GNSSAR="$gnssar"
elif [ "${codmgex^^}" == "NRT" ]; then 
  V_ORBDIR='${D}/NRT'; V_ORB="NRT"
  V_SATSYS="$satsys" ; V_GNSSAR="$gnssar"
elif [ "${codmgex^^}" == "RTM" ]; then 
  V_ORBDIR='${D}/RTM'; V_ORB="RTM"
  V_SATSYS="$satsys" ; V_GNSSAR="$gnssar"

elif [ "${codmgex^^}" == "ULT" ]; then 
  V_ORBDIR='${D}/ULT'; V_ORB="ULT"
  V_SATSYS="$satsys" ; V_GNSSAR="$gnssar"

fi

# loop over days
ymd=$edate
while [ $ymd -le $edate ];  do
    year=${ymd:0:4}
    doy=`date -d $ymd +%j`
    echo "ymd, year, doy:" $ymd $year $doy
    S0=`date -u -d "19800106 00:00:00" +%s`
    S1=`date -u -d $ymd +%s`
    gdays=`echo "($S1-$S0)/86400" | bc`
    gweek=`echo "$gdays/7" | bc`
    gday=`echo "$gdays%7" | bc`
    echo "gweek, gday: " $gweek $gday
    mjday=`echo "$gdays+44244" | bc` ; echo "mjday: " $mjday
    mjday=$mjday.000000
    datapool_subdir='${D}'/${codmgex^^}${sat}/${year}${doy}
    
    V_ORBDIR=${datapool_subdir}
    attdir=${datapool_subdir}
    rnxdir=${datapool_subdir}

    ###############################################
    # customize MENU inp files
    ###############################################
    # CPU PID tag for inp file names
    ptag=${bern_antid^^}.$gweek$gday${HM}
    campaign=${bern_antid^^}${year:2:4}${doy}${HM}

    # customize the LEOPOD.PCF, COD/COM for single/multiple gnss
    leopod_pcf=${U}/PCF/${campaign}.PCF
    bpe_leopod_pcf='${U}/PCF/'${campaign}.PCF
    cp -f ${bern_inp}/LEOPOD.PCF.${codmgex^^} ${leopod_pcf}
    echo "cp  ${bern_inp}/LEOPOD.PCF.${codmgex^^} ${leopod_pcf}"
    #cp -f ${bern_inp}/TEST.PCF ${leopod_pcf}

    leopod_cpu=${U}/PAN/${campaign}.CPU
    bpe_cpu='${U}/PAN/'${campaign}.CPU
    cp -f ${U}/PAN/USER.CPU ${leopod_cpu}
    echo "cp -f ${U}/PAN/USER.CPU ${leopod_cpu}"

    sed -Ei "s|(V_LEO\s*=\s*).*;|\1$bernid;|g" ${leopod_pcf}
    sed -Ei "s|(V_LEONUM\s*=\s*).*;|\1$leonum;|g" ${leopod_pcf}
    sed -Ei "s|(V_STAINF\s*=\s*).*;|\1$vstainf;|g" ${leopod_pcf}
    sed -Ei "s|(V_SATINF\s*=\s*).*;|\1$vsatinf;|g" ${leopod_pcf}
    sed -Ei "s|(V_ABBINF\s*=\s*).*;|\1$vstainf;|g" ${leopod_pcf}
    sed -Ei "s|(V_CRDINF\s*=\s*).*;|\1$vstainf;|g" ${leopod_pcf}
    sed -Ei "s|(V_RNXDIR\s*=\s*).*;|\1$rnxdir;|g" ${leopod_pcf}
    sed -Ei "s|(V_RNXFIL\s*=\s*).*;|\1$rnx;|g" ${leopod_pcf}
    sed -Ei "s|(V_ATTDIR\s*=\s*).*;|\1$attdir;|g" ${leopod_pcf}
    sed -Ei "s|(V_ATTFIL\s*=\s*).*;|\1$att;|g" ${leopod_pcf}
    sed -Ei "s|(V_ORBDIR\s*=\s*).*;|\1${V_ORBDIR};|g" ${leopod_pcf}
    sed -Ei "s|(V_ORB\s*=\s*).*;|\1${V_ORB};|g" ${leopod_pcf}
    sed -Ei "s|(V_SATSYS\s*=\s*).*;|\1${V_SATSYS};|g" ${leopod_pcf}
    sed -Ei "s|(V_GNSSAR\s*=\s*).*;|\1${V_GNSSAR};|g" ${leopod_pcf}

    sed -Ei "s|(V_MEANPL\s*=\s*).*;|\1${V_MEANPL};|g" ${leopod_pcf}
    sed -Ei "s|(V_SUBMOD\s*=\s*).*;|\1${V_SUBMOD};|g" ${leopod_pcf}
    sed -Ei "s|(V_NUTMOD\s*=\s*).*;|\1${V_NUTMOD};|g" ${leopod_pcf}
    sed -Ei "s|(V_PCV\s*=\s*).*;|\1${V_PCV};|g" ${leopod_pcf}
    sed -Ei "s|(V_SAMPL\s*=\s*).*;|\1${V_SAMPL};|g" ${leopod_pcf}

    sed -Ei "s|(V_SAV\s*=\s*).*;|\1${V_SAV};|g" ${leopod_pcf}
    sed -Ei "s|(V_SAVOBS\s*=\s*).*;|\1${V_SAVOBS};|g" ${leopod_pcf}

    # 1. file: MENU.INP
    menu_inp=${bern_inp}/MENU.INP.$ptag
    cp ${bern_inp}/MENU.INP ${menu_inp}
    sed -Ei "s|(\{P\}\/)\w+|\1$campaign|g" ${menu_inp}
    sed -Ei "s|(MODJULDATE\s+[0-9]+\s+\")[0-9\.]+|\1$mjday|g" ${menu_inp}

    # 2. file: MENU_RUNBPE.INP
    runpcf_inp=${bern_inp}/MENU_RUNPCF.INP.$ptag
    runbpe_inp=${bern_inp}/RUNBPE.INP.$ptag
    
    cp ${bern_inp}/MENU_RUNPCF.INP ${runpcf_inp}
    ffnt=${runbpe_inp//\//\\\/}
    sed -Ei "s|(RUN_BPE\s+[0-9]+\s+\").*\"|\1$ffnt\"|g" ${runpcf_inp}

    # 3. file: RUNBPE.INP
    cp ${bern_inp}/RUNBPE.INP ${runbpe_inp}
    sed -Ei "s|(\{P\}\/)\w+|\1$campaign|g" ${runbpe_inp}
    sed -Ei "s|(\"V_MEANPL\"\s+\").*|\1${V_MEANPL}\"|g" ${runbpe_inp}
    sed -Ei "s|(\"V_SUBMOD\"\s+\").*|\1${V_SUBMOD}\"|g" ${runbpe_inp}
    sed -Ei "s|(\"V_NUTMOD\"\s+\").*|\1${V_NUTMOD}\"|g" ${runbpe_inp}
    sed -Ei "s|(\"V_PCV\"\s+\").*\"|\1${V_PCV}\"|g" ${runbpe_inp}
    sed -Ei "s|(\"V_ORBDIR\"\s+\").*\"|\1${V_ORBDIR}\"|g" ${runbpe_inp}
    sed -Ei "s|(\"V_ORB\"\s+\").*\"|\1${V_ORB}\"|g" ${runbpe_inp}
    sed -Ei "s|(\"V_SATSYS\"\s+\").*\"|\1${V_SATSYS}\"|g" ${runbpe_inp}
    sed -Ei "s|(\"V_GNSSAR\"\s+\").*\"|\1${V_GNSSAR}\"|g" ${runbpe_inp}

      # LEOPOD
    
    sed -Ei "s|(^PCF_FILE\s+[0-9]+\s+\").*\"|\1${bpe_leopod_pcf}\"|g" ${runbpe_inp}
    #sed -Ei "s|(^CPU_FILE\s+[0-9]+\s+\").*\"|\1${bpe_cpu}\"|g" ${runbpe_inp}
    sed -Ei "s|(^\s+#\s+)LEOPOD|\1${campaign}|g" ${runbpe_inp}

    # info from LEO PCF
    sed -Ei "s|(\"V_LEO\" \").*\"|\1$bernid\"|g" ${runbpe_inp}
    sed -Ei "s|(\"V_LEONUM\" \").*\"|\1$leonum\"|g" ${runbpe_inp}
    sed -Ei "s|(\"V_RNXDIR\" \").*\"|\1$rnxdir\"|g" ${runbpe_inp}
    sed -Ei "s|(\"V_RNXFIL\" \").*\"|\1$rnx\"|g" ${runbpe_inp}
    sed -Ei "s|(\"V_ATTDIR\" \").*\"|\1$attdir\"|g" ${runbpe_inp}
    sed -Ei "s|(\"V_ATTFIL\" \").*\"|\1$att\"|g" ${runbpe_inp}
    sed -Ei "s|(\"V_STAINF\" \").*\"|\1$vstainf\"|g" ${runbpe_inp}
    sed -Ei "s|(\"V_SATINF\" \").*\"|\1$vsatinf\"|g" ${runbpe_inp}
    sed -Ei "s|(\"V_ABBINF\" \").*\"|\1$vstainf\"|g" ${runbpe_inp}
    sed -Ei "s|(\"V_CRDINF\" \").*\"|\1$vstainf\"|g" ${runbpe_inp}
    sed -Ei "s|(^YEAR\s+[0-9]+\s+\").*\"|\1$year\"|g" ${runbpe_inp}
    if [[  ${session^^} == "HOURLY" ]]; then 
       sed -Ei "s|(^SESSION\s+[0-9]+\s+\").*\"|\1${doy}A\"|g" ${runbpe_inp}
       sed -Ei "s|(SESSION_CHAR\s+[0-9]+\s+\")[0-9\.]+|\1A|g" ${menu_inp}
    else
       sed -Ei "s|(^SESSION\s+[0-9]+\s+\").*\"|\1${doy}0\"|g" ${runbpe_inp}
       sed -Ei "s|(SESSION_CHAR\s+[0-9]+\s+\")[0-9\.]+|\10|g" ${menu_inp}
    fi

    ###############################################
    # Create the session 
    ###############################################
    camphome=${P}/$campaign
    if [ -d ${P}/${campaign} ]; then rm -fr ${P}/${campaign}/* ; fi
    if [ ! -d ${camphome}/GEN ]; then mkdir -p ${camphome}/GEN ; fi
    echo "cp ${CONFIG}/OBSERV_COD.SEL ${camphome}/GEN"
    cp ${CONFIG}/OBSERV_COD.SEL ${camphome}/GEN
    if [[  ${session^^} == "HOURLY" ]]; then 
       echo "python  ${podgen_home}/PreProc/bern_sessions.py leornx_files \
          $mission $satidx $antidx $ymd > ${camphome}/GEN/SESSIONS.SES"
       #python ${podgen_home}/PreProc/bern_sessions.py leornx_files \
       #   $mission $satidx $antidx $ymd > ${camphome}/GEN/SESSIONS.SES
      cp ${podgen_home}/RunBern54/SESSIONS.SES.HOURLY ${camphome}/GEN/SESSIONS.SES
    else
       echo "python ${podgen_home}/PreProc/bern_sessions.py start_end_times \
       $stime $etime  > ${camphome}/GEN/SESSIONS.SES"
          
       python ${podgen_home}/PreProc/bern_sessions.py  start_end_times \
        "$stime" "$etime"  > ${camphome}/GEN/SESSIONS.SES
    fi
    campsubs=(ATM BPE GRD OBS ORB ORX OUT RAW SOL STA)
    for p in "${campsubs[@]}"; do
      if [ ! -d ${camphome}/$p ]; then 
         mkdir -p ${camphome}/$p ; fi
    done
    #cp -f $D/REF54/CODE.STA ${camphome}/STA/CODE.STA
    #cp -f $D/REF54/UMD_LEO.STA ${camphome}/STA/UMD_LEO.STA
    #cp -f $D/REF54/EXAMPLE.CRD ${camphome}/STA/EXAMPLE.CRD

    # run
    if [ "$debug" == "0" ]; then
       echo "Begin Bernese"
       echo "${XQ}/menu ${menu_inp} ${runpcf_inp}"
       date
       #screen -S bns -m ${XQ}/menu ${menu_inp} ${runpcf_inp}
       ${XQ}/menu ${menu_inp} ${runpcf_inp}
       rm -f ${menu_inp} ${runbpe_inp} ${runpcf_inp} ${leopod_pcf} ${leopod_cpu}
       date
       echo "End Bernese"
    else
       echo "PCF file: ${leopod_pcf}"
       echo "RUNBPE : ${runbpe_inp}"
    fi
    ymd=`date -d "$ymd +1 day" +%Y%m%d`
done


exit 0




