#!/bin/bash

set -xuve

#griddir=/gpfs/scratch/bsc32/bsc32051/pub/scripts/convert-tm5-grids
griddir=.

newdate=$1
#taxis="settaxis,21450101,00:00:00,1day"
taxis="settaxis,$newdate,00:00:00,1day"

gridname_ifs=L128
griddef_ifs=ICMGGa22e+000000 # copy from /gpfs/scratch/bsc32/bsc32051/pub/scripts/convert-tm5-grids
gridname_AMIP=AMIP
griddef_amip=grid-amip.txt # cdo griddes tosbcs_input4MIPs_SSTsAndSeaIce_CMIP_PCMDI-AMIP-1-1-3_gn_187001-201706.nc > grid-amip.txt
gridname_co2=CO2
griddef_co2=grid-co2_emis.txt # cdo griddes  > grid-co2_emis.txt
model_ifs=IFS_TOY

# set vars according to model_mode
# TODO: They will be replaced by python YAML reader 

[ $model_mode = "co2box" ] && CO2BOX=true || CO2BOX=false
[ $model_mode = "co2flux" ] && CO2FLUX=true || CO2FLUX=false

if [[ ${CO2BOX} == true ]] ; then
    grids=""
    vars_amip=""
    vars_ifs=""
    model_amip=CO2BOX
    model_co2=CO2BOX
    vars_co2=""
    vars_co2_co2box="CO2BOX_CO2_cconc CO2BOX_CO2_econc"
    vars_co2_ifs="A_CO2_cconc A_CO2_econc"
else
    grids="AMIP L128" #B128 A128 R128
    [[ ${CO2FLUX} == true ]] && grids+=" CO2_emis"
    vars_amip="AMIP_sst AMIP_sic"
    vars_ifs="A_SST A_Ice_frac"
    [[ ${CO2FLUX} == true ]] && vars_ifs+=" A_CO2_emis A_CO2_land A_CO2_ocean"
    model_amip=AMIPFORC
    model_co2=AMIPFORC
    [[ ${CO2FLUX} == true ]] && vars_co2="AMIP_CO2_emis" || vars_co2=""
    vars_co2_co2box=""
    vars_co2_ifs=""
fi

# copy from runtime dir the following files grids.nc areas.nc masks.nc
for gridname in ${grids}
do
    if [[ ${gridname} == AMIP ]] ; then
	format=nc
	suffix=".nc"
	griddef=${griddef_amip}
    elif [[ ${gridname} == CO2_emis ]] ; then
	format=nc
	suffix=".nc"
	griddef=${griddef_co2}
    else
	format=grb1
	suffix=".grb"
	griddef=${griddef_ifs}
    fi
    cdo -f $format -setgrid,${griddir}/${griddef} -selvar,${gridname}.msk masks.nc masks_${gridname}${suffix}
    cdo -f $format -setgrid,${griddir}/${griddef} -selvar,${gridname}.srf areas.nc areas_${gridname}${suffix}
    if [[ ${format} == "grb1" ]] ; then
        for t in masks areas ; do
            cdo -f nc -setgridtype,regularnn ${t}_${gridname}.grb ${t}_${gridname}.nc
        done
    fi
done


for v in $vars_ifs
do
    cdo -O -f grb1 -r $taxis -setgrid,${griddir}/${griddef_ifs} ${v}_${model_ifs}_??.nc ${v}.grb
    cdo -O -f nc   -r $taxis -setgridtype,regular -chvar,var1,${v} ${v}.grb ${v}.nc
done

for v in $vars_amip
do
    HDF5_DISABLE_VERSION_CHECK=1 cdo -O -f nc -r $taxis -setgrid,${griddir}/${griddef_amip} ${v}_${model_amip}_??.nc ${v}.nc
done

for v in $vars_co2
do
    HDF5_DISABLE_VERSION_CHECK=1 cdo -O -f nc -r $taxis -setgrid,${griddir}/${griddef_co2} ${v}_${model_co2}_??.nc ${v}.nc
done
for v in $vars_co2_co2box
do
    HDF5_DISABLE_VERSION_CHECK=1 cdo -O -f nc -r $taxis ${v}_${model_co2}_??.nc ${v}.nc
done
for v in $vars_co2_ifs
do
    HDF5_DISABLE_VERSION_CHECK=1 cdo -O -f nc -r $taxis ${v}_${model_ifs}_??.nc ${v}.nc
done
