#!/bin/bash

# This script searches for VIIRS granules within +/- 30 minutes of a user specified time and within 50 degrees
# of either pole,generating a list of files that are then copied to the local L1B working directory.
# Required inputs include the satellite name ("npp", "j01"  or "j02"), the date (yyyyddd) and time (hhmm) 
#
# All granule files required to process VPW are copied to the working l1b sat directory. 

# Read the user-entered fields
vsat=$1 # ("npp", "j01"  or "j02")

# Start day and time for search
yyyyddd1=$2 # 4-digit year and 3-digit Julian Day (e.g. 2022166) of entered time
hh1=$3 # hour
mm1=$4 # minute

# End day and time for search
yyyyddd2=$5 # 4-digit year and 3-digit Julian Day (e.g. 2022166) of entered time
hh2=$6 # hour
mm2=$7 # minute

# Set l1b working directory for current sat being processed. 
vsat_out_path=/data/smcd8/abailey/run_ASF_VIIRS_Tandem_Winds/${vsat}/

# All the L1b file types needed from SCDR for VPW processing: remap/stitching of granules, clouds, winds. 
L1b_FileType=( GDNBO GITCO GMTCO SVDNB SVI05 SVM01 SVM05 SVM07 SVM09 SVM10 SVM11 SVM12 SVM13\
               SVM14 SVM15 SVM16 )

echo ' ' 
echo "Start processing time: "$(date)

# Parse the date and time
year1=${yyyyddd1:0:4}
jd3=${yyyyddd1:4:3}
jd1=$(echo $jd3 | awk '{$0=int($0)}1')

year2=${yyyyddd2:0:4}
jd3=${yyyyddd2:4:3}
jd2=$(echo $jd3 | awk '{$0=int($0)}1')

hh1=$(echo $hh1 | awk '{$0=int($0)}1')
hh2=$(echo $hh2 | awk '{$0=int($0)}1')

# Build date/time strings for scdr-files query using 'date' command
yymmdd1=$(date -d "$year1-01-01 +$(( $jd1 - 1 )) days +$(( $hh1 )) hours +$(( $mm1 )) minutes" +%Y-%m-%d' '%H:%M:00)
yymmdd3=$(date -d "$year2-01-01 +$(( $jd2 - 1 )) days +$(( $hh2 )) hours +$(( $mm2 + 30 )) minutes" +%Y-%m-%d' '%H:%M:59)

echo "search window: $yymmdd1 to $yymmdd3"
echo ' '

# get listing of geolocation granules from SCDR
file=($(/data/starfs1/bin/scdr-files -t GDNBO --stime "$yymmdd1" --etime "$yymmdd3" |grep $vsat))

# Loop through all data types required for VPW processing, filter out and copy relevant granules to working directory
for (( j = 0 ; j < 16 ; j++ ))
do
  rm image_list_$vsat
  rm filtered_image_list_$vsat

  # create file with listing of image granules
  echo "/data/starfs1/bin/scdr-files -t ${L1b_FileType[$j]} --stime "$yymmdd1" --etime "$yymmdd3" "
  /data/starfs1/bin/scdr-files -t ${L1b_FileType[$j]} --stime "$yymmdd1" --etime "$yymmdd3" |grep $vsat >image_list_$vsat

  # Check for duplicate granules present on SCDR (it happens more than you'd think) and filter out of list.
  # It'll screw up the cloud algorithms if you don't.
  awk -F'_' '!seen[$3$4]++' image_list_$vsat > filtered_image_list_$vsat
  cp ./filtered_image_list_$vsat ./image_list_$vsat

  image_granule_file=($(cat image_list_$vsat))

  # Remove old working files
  rm file_center_pts_$vsat
  rm filtered_file_list_$vsat
  rm filtered_granule_list_$vsat

  # Loop through file list and create a new file with lat/lon center point added to each 
  # line of original list. This will be used to filter on latitude below. 
  for (( i = 0 ; i < ${#image_granule_file[@]} ; i++ ))
  do
    # Strip lat/lon from mid point of granule
    dummy=$(ncks -v Latitude,Longitude -F -dphony_dim_0,384 -dphony_dim_1,1600 ${file[$i]} | awk '/} ;/{print $1}' | sed 's/{//' | sed 's/}//')

    echo ${file[$i]} $dummy >>file_center_pts_$vsat
  done

  # Create filtered list of granules within 50 degrees of each pole
  cat file_center_pts_$vsat | awk '($2 <= -50 || $2 >= 50){print $1}'>>filtered_file_list_$vsat

  # Check for duplicate granules present on SCDR (it happens) and filter out of list.
  # (it'll screw up the cloud algorithms if you don't)
  awk -F'_' '!seen[$3$4]++' filtered_file_list_$vsat > filtered_granule_list_$vsat
  cp ./filtered_granule_list_$vsat ./filtered_file_list_$vsat

  num_granules=$(wc -l filtered_file_list_$vsat | awk '{print $1}')

  if (( $num_granules > 0 ))
  then
    echo "Found " $num_granules "granules."
  else
    echo "Did not find any granules matching criteria. Exiting..."
    exit 1
  fi

  file_filt=($(cat filtered_file_list_$vsat))

  num=0 #reset counter
  # Loop through filtered list of geolocation files and copy the geolocation
  # file and the image file corresponding to the extracted time.
  for (( i = 0 ; i < ${#file_filt[@]} ; i++ ))
  do
    # Copy data to vsat directory
    (( num+=1 ))
    (( num_total+=1 ))
    start_time=$(echo ${file_filt[$i]} | awk -F_ '{print $4}')
    scdr_group_file=$(grep $start_time image_list_$vsat)
    cp $scdr_group_file $vsat_out_path
  done

  echo "Copied" $num "granules for group ${L1b_FileType[$j]}"
  echo ' '

done  # End file types loop

echo "Done! Total granules copied: $num_total"
echo ' '

echo "end processing time: "$(date)

