#!/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
model_ifs=IFS_MOCK
vars_ifs="A_SST A_Ice_frac"
model_amip=AMIPFORC
vars_amip="AMIP_sst AMIP_sic"

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



# copy from a runtime dir the following files grids.nc areas.nc masks.nc

for gridname in AMIP L128 # B128 A128 R128
do
    if [[ ${gridname} == AMIP ]] ; then
	format=nc
	suffix=".nc"
	griddef=${griddef_amip}
    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}
done

for gridname in L128 # B128 A128 R128
do
cdo -f nc -setgridtype,regularnn masks_${gridname}.grb masks_${gridname}.nc
cdo -f nc -setgridtype,regularnn areas_${gridname}.grb areas_${gridname}.nc
done
