#!/bin/bash 

#SBATCH -n 1
#SBATCH -t 23:59:59
#SBATCH -J week_year_ 
#SBATCH -e /esarchive/recon/ecmwf/era5/scripts/out-logs/week-%j.err
#SBATCH -o /esarchive/recon/ecmwf/era5/scripts/out-logs/week-%j.out

module load CDO
tmp_dir=$NVME1DIR
y=$1

for var in prlr tasmin tasmax; do
#for var in tas tasmin tasmax psl prlr rsds sfcWind; do
  if [[ $var == "tasmin" || $var == "tasmax" ]]; then
    orig_dir=/esarchive/recon/ecmwf/era5/daily/${var}/
    dest_dir=/esarchive/recon/ecmwf/era5/weekly_mean/${var}_f24h/
    expected_steps=7
  else
    orig_dir=/esarchive/recon/ecmwf/era5/1hourly/${var}_s00-01h/
    dest_dir=/esarchive/recon/ecmwf/era5/weekly_mean/${var}_f1h/
    expected_steps=168
  fi
  for month in $(seq -w 1 12); do
    date=$(date +"%Y-%m-%d" --date "${y}-${month}-01")
    date2=$(date +"%Y-%m-%d" --date "${y}-${month}-01 + 1 month")
    month2=$(echo "$date2" | cut -d'-' -f 2)
    y2=$(echo "$date2" | cut -d'-' -f 1)
    last_day=$(date --date="${date} + 1 month -1 day" +%d)
  
    orig_file1=${orig_dir}/${var}_${y}${month}.nc
    orig_file2=${orig_dir}/${var}_${y2}${month2}.nc
    orig_file=${tmp_dir}/${var}_${y}${month}-${month2}.nc
    
  
    if [ $(ls ${dest_dir}/${var}_${y}${month}??.nc | wc -l) -ne ${last_day} ]; then
  
      cdo mergetime ${orig_file1} ${orig_file2} ${orig_file}
  	
      for day in $(seq -w 1 ${last_day}); do
  
        sd_week=$(date +"%Y-%m-%d" --date "${y}-${month}-${day}")
        for dd in $(seq 0 6); do
  	      dates[$dd]="$(date --date="${sd_week}+$dd day" +%Y-%m-%d)"
        done
        week_dates="$( IFS=$','; echo "${dates[*]}" )"
  
        if [ ! -f ${dest_dir}/${var}_${y}${month}${day}.nc ];then 
  
  	      if [ ! -f ${tmp_dir}/${var}_${y}${month}${day}.nc ]; then
  	        cdo seldate,${week_dates} ${orig_file} ${tmp_dir}/${var}_${y}${month}${day}.nc
  	      fi 
  
  	      file_dates=$(cdo showdate ${tmp_dir}/${var}_${y}${month}${day}.nc) 
  	      expected_dates=$( IFS=$' '; echo "${dates[*]}" )
          timesteps=$(cdo showtime ${tmp_dir}/${var}_${y}${month}${day}.nc)
          steps=$(echo ${timesteps[0]} | wc -w)
   
          if [ $( echo ${file_dates} | sed "s/ /_/g") == $( echo ${expected_dates} | sed "s/ /_/g") ] && [ ${steps} ==  ${expected_steps} ]; then
             cdo timmean ${tmp_dir}/${var}_${y}${month}${day}.nc ${dest_dir}/${var}_${y}${month}${day}.nc
             rm ${tmp_dir}/${var}_${y}${month}${day}.nc
          else 
              echo "WRONG DATES ${var}_${y}${month}${day}.nc"
              echo ${file_dates}
          fi
        fi
      done 
      rm ${orig_file}
    fi
  done
done

