#!/bin/bash
#
###############################################################################
# Sets environment variables, configures and runs the GOES ABI AMV algorithms #
#                   for HiRes MESO winds processing                           #
###############################################################################
#
# Script to configure and run the GOES AMV algorithm via the ASF.  
# Expects L1B imagery and Cloud data files to already exist in an Intermediate_Data/ directory. 
#
# example:  ./run_GOES_WINDS_HIRES.bash <sat> <sector> <amv_channel> <hires> <L1b_input1> <L1b_input2> <L1b_input3> 
#
#           <sat>         - Satellite to process
#                           '16' for GOES-16
#                           '17' for GOES-17
#           <sector>      - ABI sector to process
#                           'FD' Full Disk sector
#                           'CONUS' for CONUS sector
#                           'MESO1' for MESO sector 1 
#                           'MESO2' for MESO sector 2 
#           <amv_channel> - Channel (wind_type) to process
#                           '02' vis 0.5km cloud-track
#                           '07' swir cloud-track
#                           '08' wv cloud-track
#                           'cs08' wv clear-sky
#                           '09' wv clear-sky
#                           '10' wv clear-sky
#                           '14' ir cloud-track
#           <hires>       - HIRES or Nominal Resolution Job
#                           '1' Nominal Resolution 
#                           '2' High Resolution
# <HIRES_Winds_Process_Path> - Processing path for HIRES winds...set in driver script
#           <WindType>    - Wind Type being processed
#           <L1b_input1>  - First image in the triplet
#           <L1b_input2>  - Second image in the triplet
#           <L1b_input3>  - Third image in the triplet
#
# AAB 11/10/2024 - Modified for MESO HiRes 
#

# source the framework 2.0 main branch environment
source /data/smcd8/abailey/ASF_Main_Latest_wCloudyPixels_And_HIRES_MESO_Mods/AlgorithmServices/setEnvGCC.sh gcc830
#source /data/smcd8/abailey/ASF_HIRES_MESO_GCC11/AlgorithmServices/setEnvGCC11.sh gcc830


# Read inputs from command line
#
sat=$1
sector=$2 
amv_channel=$3
hires_job=$4
HIRES_Winds_Process_Path=$5
WindType=$6
L1b_input1=$7
L1b_input2=$8
L1b_input3=$9

#
# Pull out middle image time stamp for setting ENV_AIT_FILE_TIME_STAMP
#
image_time2=$(echo $L1b_input2 | awk -F_ '{print $15}')
yyyy=${image_time2:1:4}
ddd=${image_time2:5:3}
hh=${image_time2:8:2}
mm=${image_time2:10:2}
ss=${image_time2:12:2}.${image_time2:14:1}

#
# Remove any leading 0's from ddd
#
jday=$(echo $ddd | awk '{$0=int($0)}1')

#
# Convert to calendar month and day
#
yyyymmdd=$(date -d "`date +${yyyy}`-01-01 +$(( ${jday} - 1 ))days" +%Y%m%d)
cal_month=${yyyymmdd:4:2}
cal_day=${yyyymmdd:6:2}

#echo $image_time2
#echo $yyyy, $jday, $hh, $mm, $ss
#echo $yyyymmdd, $cal_month, $cal_day

# Set the scanning timeline mode. This will be used later to Check if GOES-17 is in the 
# "Flex Mode-3" Cooling Timeline. 
L1b_group=$(echo $L1b_input2 | awk -F_ '{print $13}')

if [ "${sector:0:4}" = "MESO" ]
then
  Mode=${L1b_group:14:2}
  meso_id=${L1b_group:12:1}
else
  Mode=${L1b_group:13:2}
fi
echo ' ' 
echo Mode= $Mode
echo meso_id=$meso_id
#
# Set remaining inputs based on sector and channel/windtype
#
if [ "$sector" = "FD" ] 
then
  if [ "$amv_channel" = "07" ] || [ "${amv_channel:0:2}" = "08" ] || [ "$amv_channel" = "14" ]
  then
    echo ' ' 
    echo "Processing GOES$sat $sector Channel-${amv_channel} Cloud Track AMVs for:"
    echo year=$yyyy month=$cal_month day=$cal_day hour=$hh min=$mm

    resolution="ABI_2KM"
    total_seg=8
    target_type="CT"
    nom_timestep=10

    # Check if GOES-17 is in the Flex Mode-3 Cooling Timeline. This occurs 
    # 4x/year in order to mitigate the number of saturated images resulting 
    # from the loop heat pipe (LHP) temperature regulation anomaly.
    if [ "$sat" = "17" ] && [ "$Mode" = "M3" ]
    then
      echo ' ' 
      echo "GOES-17 running Flex Mode-3 Timeline. Set timestep=15 minutes."
      nom_timestep=15
    fi

  elif [ "$amv_channel" = "cs08" ] || [ "$amv_channel" = "09" ] || [ "$amv_channel" = "10" ]
  then
    echo ' '
    echo "Processing GOES$sat $sector Channel-${amv_channel} Clear-Sky WV AMVs for:"
    echo year=$yyyy month=$cal_month day=$cal_day hour=$hh min=$mm

    resolution="ABI_2KM"
    total_seg=8
    target_type="CS"
    nom_timestep=30

  elif [ "$amv_channel" = "02" ] 
  then
    echo ' '
    echo "Processing GOES$sat $sector Channel-${amv_channel} Cloud Track AMVs for:"
    echo year=$yyyy month=$cal_month day=$cal_day hour=$hh min=$mm

    resolution="ABI_500M"
    total_seg=8
    target_type="CT"
    nom_timestep=10

    # Check if GOES-17 is in the Flex Mode-3 Cooling Timeline. This occurs 
    # 4x/year in order to mitigate the number of saturated images resulting 
    # from the loop heat pipe (LHP) temperature regulation anomaly.
    if [ "$sat" = "17" ] && [ "$Mode" = "M3" ]
    then
      echo ' '
      echo "GOES-17 running Flex Mode-3 Timeline. Set timestep=15 minutes."
      nom_timestep=15
    fi
  fi

elif [ "$sector" = "CONUS" ] 
then
  if [ "$amv_channel" = "07" ] || [ "${amv_channel:0:2}" = "08" ] || [ "$amv_channel" = "14" ]
  then
    echo ' '
    echo "Processing GOES$sat $sector Channel-${amv_channel} Cloud Track AMVs for:"
    echo year=$yyyy month=$cal_month day=$cal_day hour=$hh min=$mm

    resolution="ABI_2KM"
    total_seg=2
    target_type="CT"
    nom_timestep=5

  elif [ "$amv_channel" = "cs08" ] || [ "$amv_channel" = "09" ] || [ "$amv_channel" = "10" ]
  then
    echo ' '
    echo "Processing GOES$sat $sector Channel-${amv_channel} Clear-Sky WV AMVs for:"
    echo year=$yyyy month=$cal_month day=$cal_day hour=$hh min=$mm

    resolution="ABI_2KM"
    total_seg=2
    target_type="CS"
    nom_timestep=30

  elif [ "$amv_channel" = "02" ]
  then
    echo ' '
    echo "Processing GOES$sat $sector Channel-${amv_channel} Cloud Track AMVs for:"
    echo year=$yyyy month=$cal_month day=$cal_day hour=$hh min=$mm
    echo ' '

    resolution="ABI_500M"
    total_seg=2
    target_type="CT"
    nom_timestep=5
  fi
elif [ "${sector:0:4}" = "MESO" ]
then
  if [ "$amv_channel" = "07" ] || [ "${amv_channel:0:2}" = "08" ] || [ "$amv_channel" = "14" ]
  then
    echo ' '
    echo "Processing GOES$sat $sector Channel-${amv_channel} Cloud Track AMVs for:"
    echo year=$yyyy month=$cal_month day=$cal_day hour=$hh min=$mm

    resolution="ABI_2KM"
    total_seg=2
    target_type="CT"
    nom_timestep=1

  elif [ "$amv_channel" = "cs08" ] || [ "$amv_channel" = "09" ] || [ "$amv_channel" = "10" ]
  then
    echo ' '
    echo "Processing GOES$sat $sector Channel-${amv_channel} Clear-Sky WV AMVs for:"
    echo year=$yyyy month=$cal_month day=$cal_day hour=$hh min=$mm

    resolution="ABI_2KM"
    total_seg=2
    target_type="CS"
    nom_timestep=30

  elif [ "$amv_channel" = "02" ]
  then
    echo ' '
    echo "Processing GOES$sat $sector Channel-${amv_channel} Cloud Track AMVs for:"
    echo year=$yyyy month=$cal_month day=$cal_day hour=$hh min=$mm
    echo ' '

    resolution="ABI_500M"
    total_seg=2
    target_type="CT"
    nom_timestep=1
  fi
fi

# Set output data directory path
# Set WindType based on channel #
if [[ $amv_channel = 14 ]]; then WindType=ircd;fi
if [[ $amv_channel = 07 ]]; then WindType=swcd;fi
if [[ $amv_channel = 02 ]]; then WindType=vzcd;fi
if [[ "${amv_channel:0:2}" = "08" ]]; then WindType=wvcd;fi
if [[ "$amv_channel" = "cs08" ]]; then WindType="wvcs08";fi
if [[ $amv_channel = 09 ]]; then WindType=wvcs09;fi
if [[ $amv_channel = 10 ]]; then WindType=wvcs10;fi

if [ "${sector:0:4}" = "MESO"  ]
 then
   if [ $hires_job = 1 ]
    then
#     output_data_path=./GOES-${sat}_Reprocess/${sector}/${WindType}/
#     export ENV_HIRES_JOB=1
      echo " "
      echo "======================================================================================= "
      echo "ERROR: Yea, sorry...script currently only supports hires runs."
      echo "ERROR: Use any one of the Nominal Resolution bash scripts to run ENV_HIRES_JOB=1"
      echo "ERROR: I'll write a single functional script at some point."
      echo "ERROR: Maybe."
      echo "ERROR: OK, who am I kidding? I doubt I'll ever get around to doing that."
      echo "ERROR: Don't like it? Write your own damn script."
      exit 1
   else
     output_data_path=$HIRES_Winds_Process_Path${WindType}/
     export ENV_HIRES_JOB=2
   fi
fi

echo ' '
echo 'ENV_HIRES_JOB= ' $ENV_HIRES_JOB
echo 'output_data_path= ' $output_data_path

# Reset clear-sky Ch08 channel input variable to remove 'cs' for later processing
if [ "$amv_channel" = "cs08" ]; then amv_channel=08;fi

#
# Export algorithm processing environmental variables from above inputs
#
export ENV_SATELLITE=GOES$sat
# If running MESO, trim sector input for algorithms...
if [ "${sector:0:4}" = "MESO" ]
then
  export ENV_COVERAGE=${sector:0:4}
else
  export ENV_COVERAGE=$sector
fi
export ENV_WINDS_PRODUCT_RESOLUTION=$resolution
TOTAL_SEG=$total_seg                    #preset within configuration already.
export ENV_AMV_CHANNELS="${amv_channel:0:2}"
#export ENV_AMV_CHANNELS="02,07,08,14"
export ENV_WINDS_TARGET_TYPE=$target_type
export ENV_NOMINAL_TIMESTEP="step${nom_timestep}min" #step1min,step5min,step10min,step15min, etc.
export ENV_FIRST_IMAGE=$L1b_input1
export ENV_MIDDLE_IMAGE=$L1b_input2
export ENV_LAST_IMAGE=$L1b_input3
export ENV_AIT_FILE_TIME_STAMP="{year=$yyyy;month=$cal_month;day=$cal_day;hour=$hh;min=$mm;sec=$ss}"

#
# Export environmental variables for output and input directory
#
#export ENV_OUTPUT_DIRECTORY="./Output/"
export ENV_OUTPUT_DIRECTORY="${output_data_path}"
#export ENV_INPUT_DIRECTORY="./GOES-${sat}_Reprocess/Intermediate_Data_${sector}/"
export ENV_INPUT_DIRECTORY="${HIRES_Winds_Process_Path}Intermediate_Data_HIRES_${sector}/"

#
# LUT data directory (for ABI reader).
#
export ENV_FRAMEWORK_ANCILLARY_DIR="../static_datasets/framework_ancillary/"

#
# Path to configuration XML
#
CFG="./Config/Projects/AIT_ABI_EN/Config-WINDS_UNIT.xml"
CMD="./algorithms.exe"

##############################################################
# Call a sequential or parallel run
##############################################################

parallelRun=true

if [ "$parallelRun" != true ]
then
    bash Config/Projects/Sample_Execution/run_sequential_execution.sh ${CFG}
else
    if [ "$amv_channel" = "02" ]
    then
      MAX_JOBS=2
    else
      MAX_JOBS=4
    fi

    echo ' ' 
    echo MAX_JOBS= $MAX_JOBS

#   TOTAL_SEG=8 #this is fixed to the segmentation that was tested, otherwise: $(($ENV_NUM_COL_SEG * $ENV_NUM_ROW_SEG))
    TOTAL_SEG=$total_seg #this is fixed to the segmentation that was tested, otherwise: $(($ENV_NUM_COL_SEG * $ENV_NUM_ROW_SEG))
    #JOB_ID="AMV_${sector}_${WindType}_framework_job_${Middle_Image_Time}_$$"
    JOB_ID="AMV_${sector}_${WindType}_framework_job_${Middle_Image_Time}"

    echo ' '
    echo "bash Config/Projects/Sample_Execution/run_parallel_execution.sh ${CFG} ${JOB_ID} ${TOTAL_SEG} ${MAX_JOBS}"
          bash Config/Projects/Sample_Execution/run_parallel_execution.sh ${CFG} ${JOB_ID} ${TOTAL_SEG} ${MAX_JOBS}
fi

#
# Move ASCII file to proper output directory
#
mv ASCII_AMV.GOES${sat}.${yyyy}${ddd}.${hh}${mm}.CH_${amv_channel}.*.${target_type} $ENV_OUTPUT_DIRECTORY


##############################################################

date


