#!/bin/bash

# compares runs and reruns to remove duplicates

outdir_base=/tank/exports/ERC_PALAEO
setlist=HIPPO_set_1400_1

for set in ${setlist}; do

   cd ${outdir_base}/${set}

   runlist=$(ls -d HIPPO_r???i????p?f*)

   for run in ${runlist}; do

#      reffile=mon.special.nc ; refdir=${outdir_base}/${set}/${run}/means; diff="cdo -s diff"
#      reffile=mon.stdlevs.nc ; refdir=${outdir_base}/${set}/${run}/means; diff="cdo -s diff"
#      reffile=mon.meridional.nc ; refdir=${outdir_base}/${set}/${run}/means; diff="cdo -s diff"
      reffile=mon.toasurf.nc ; refdir=${outdir_base}/${set}/${run}/means; diff="cdo -s diff"
#      reffile=12.01_echam; refdir=${outdir_base}/${set}/${run}/rawdata; diff="diff"

      cd ${refdir}

      filelist=$(ls rerun_${run}_????_${reffile})
#      filelist=$(ls rerun_${run}_????${reffile})

      for file in ${filelist}; do

         year=$(echo ${file} | sed -e "s/rerun_${run}_//" | sed -e "s/_${reffile}//" | cut -c 1-4 )

         ${diff} ${file} ${file/rerun_/} &&
         echo "${file} and ${file/rerun_/} agree, ${year}, renaming. " &&
         rename -f "s/rerun_//" ${outdir_base}/${run}/rawdata/rerun_${run}_${year}??.01_{echam,accw} && 
         rename -f "s/rerun_//" ${outdir_base}/${run}/means/rerun_${run}_${year}_*.{grb,nc} &&
         rename -f "s/rerun_//" ${outdir_base}/${run}/restart/restart_rerun_${run}_${year}1231??????_*.nc ||
         echo ${file}

      done # file in filelist

   done  # run in runlist

done # set in setlist

exit 0
