#!/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_MOCK
vars_ifs="A_SST A_Ice_frac"
[[ `grep CO2_conc namcouple` != "" ]] && CO2_MODE=true || CO2_MODE=false
[[ ${CO2_MODE} == true ]] && vars_ifs+=" A_CO2_emis"

model_amip=AMIPFORC
vars_amip="AMIP_sst AMIP_sic"
model_co2=AMIPFORC
[[ ${CO2_MODE} == true ]] && vars_co2="AMIP_CO2_emis" || vars_co2=""
grids="AMIP L128" #B128 A128 R128
[[ ${CO2_MODE} == true ]] && grids+=" CO2_emis"

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


# copy from a 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

