data_ini=$1
data_end=$2

dir_out=/p/projetos/monan_goc/dados_goc/ERA5/fluxos
data=$data_ini

while [[ $data -le $data_end ]] ; do

echo ${data}
year=${data:0:4}
month=${data:4:2}

\rm -f fluxes.py

cat > fluxes.py << EOF

import cdsapi

dataset = "reanalysis-era5-single-levels-monthly-means"
request = {
    "product_type": ["monthly_averaged_reanalysis"],
    "variable": [
        "surface_latent_heat_flux",
        "surface_sensible_heat_flux"
    ],
    "year": ["${year}"],
    "month": ["${month}"],
    "time": ["00:00"],
    "data_format": "netcdf",
    "download_format": "unarchived"
}

client = cdsapi.Client()
client.retrieve(dataset, request).download(
        "${dir_out}/era5_fluxes_monthly_${month}${year}.nc"
)
EOF
chmod u+wx fluxes.py
python fluxes.py
\rm -f fluxes.py

data=$(date -u "+%Y%m" -d "${year}${month}01 00:00 1 month")

done
