#!/bin/csh

#
#script to dowload MERRA2 data.
# Ashwanth Srinivasan Tendral LLC.
# Initial version: 2018/05/01
# Changes: added some documentation. 2018/07/02

#see Bosilovich et al. report on MERRA2, for details on dataset and available variables: https://ntrs.nasa.gov/search.jsp?R=20150019760
#need to register with Earthdata Login and then authorize NASA GESDISC Data Access. 
#Instructions are here: https://disc.gsfc.nasa.gov/registration/registration-for-data-access

set AD=/pesq/share/oceanwave/dist/MONAN/MERRA2/2016/test_download
set DD=/pesq/share/oceanwave/dist/MONAN/MERRA2/2016/test_download
set MA=https://goldsmr4.gesdisc.eosdis.nasa.gov/opendap/MERRA2/M2I1NXASM.5.12.4
set MF=https://goldsmr4.gesdisc.eosdis.nasa.gov/opendap/MERRA2/M2T1NXFLX.5.12.4
set MR=https://goldsmr4.gesdisc.eosdis.nasa.gov/opendap/MERRA2/M2T1NXRAD.5.12.4
set DE=400 # decadal number; 300 for 2000-2010; 400 for 2011-present

# we set the script up to download files yearly by providing a start and end day for a chosen year.
# for example to download for 2008; we have to provide a start and an end day.
# start day is the number of elapsed days from the start we want and today. 
# say we want Jan 2008/01/01 then start day will be no of days betwen 2007/12/31 and today (2018/07/02) ie 3836 days
# date +%Y%m%d -d "3836 days ago" gives 20071231
# end day will be 365(6) days after start day
# here it will be 366 days since 2008 was a leap year.

set stday = 3127 # start day is the number of days elapsed since the start day w>
set enday = 3127 # end day is 365(6(days before the start day)


foreach dm (`seq $stday -1 $enday`)
set YMD = `date +%Y%m%d -d "$dm days ago" `
set M=`date +%m -d "$dm days ago" `
set Y=`date +%Y -d "$dm days ago" `
echo $YMD $M $Y

wget -v --user=rosio.camayo --password=u5czm29P?u@8v9J "${MA}/${Y}/${M}/MERRA2_${DE}.inst1_2d_asm_Nx.${YMD}.nc4.nc?T10M&accept=netcdf" -O ${DD}/T10M_${YMD}.nc
wget -v --user=LOGIN --password=SENHA_DO_LOGIN "${MA}/${Y}/${M}/MERRA2_${DE}.inst1_2d_asm_Nx.${YMD}.nc4.nc?U10M&accept=netcdf" -O ${DD}/U10M_${YMD}.nc
wget -v --user=LOGIN --password=SENHA_DO_LOGIN "${MA}/${Y}/${M}/MERRA2_${DE}.inst1_2d_asm_Nx.${YMD}.nc4.nc?V10M&accept=netcdf" -O ${DD}/V10M_${YMD}.nc
wget -v --user=LOGIN --password=SENHA_DO_LOGIN "${MA}/${Y}/${M}/MERRA2_${DE}.inst1_2d_asm_Nx.${YMD}.nc4.nc?QV10M&accept=netcdf" -O ${DD}/QV10M_${YMD}.nc
wget -v --user=LOGIN --password=SENHA_DO_LOGIN "${MA}/${Y}/${M}/MERRA2_${DE}.inst1_2d_asm_Nx.${YMD}.nc4.nc?TS&accept=netcdf" -O ${DD}/TS_${YMD}.nc
wget -v --user=LOGIN --password=SENHA_DO_LOGIN "${MF}/${Y}/${M}/MERRA2_${DE}.tavg1_2d_flx_Nx.${YMD}.nc4.nc?PRECTOTCORR&accept=netcdf" -O ${DD}/PCIP_${YMD}.nc
wget -v --user=LOGIN --password=SENHA_DO_LOGIN "${MR}/${Y}/${M}/MERRA2_${DE}.tavg1_2d_rad_Nx.${YMD}.nc4.nc?LWGNT&accept=netcdf" -O ${DD}/LWNT_${YMD}.nc
wget -v --user=LOGIN --password=SENHA_DO_LOGIN "${MR}/${Y}/${M}/MERRA2_${DE}.tavg1_2d_rad_Nx.${YMD}.nc4.nc?SWGNT&accept=netcdf" -O ${DD}/SWNT_${YMD}.nc

end
