#!/bin/bash
#
# copies the ModE-Sim files from the old structure ("HIPPO_r???i????p?f????) to the new structure (ModE-Sim_m???)
#
# ralf.hand@giub.unibe.ch, 10.02.2023

set -ex

overviewfile=/tank/exports/ERC_PALAEO/ModE-Sim/docu/ModE-Sim_overview.csv

outdir_base=/tank/exports/ERC_PALAEO/ModE-Sim/test

col_orig_set=$(head -1 ${overviewfile} | awk -F ";" -v b="orig_set" '{for (i=1;i<=NF;i++) { if ($i == b) { print i } }}')
col_orig_member=$(head -1 ${overviewfile} | awk -F ";" -v b="orig_member" '{for (i=1;i<=NF;i++) { if ($i == b) { print i } }}')

# for final_set in 1420-1 1420-2 1420-3 1850-1 1850-2 H-1400-1 H-1850-1 H-1870-1; do
for final_set in 1420-3-ext; do

   for final_member in $(cat ${overviewfile} | grep "^${final_set};m[0-9][0-9][0-9];" | awk -F ";" '{print $2}' | sort -u) ; do

      n_orig_sets=$(grep "${final_set};${final_member}" ${overviewfile} | wc -l)
   
      for i in $(seq 1 ${n_orig_sets}); do

         orig_set=$(grep "${final_set};${final_member}" ${overviewfile} | awk -F ';' "NR==${i} {print \$$(echo ${col_orig_set})}")
         orig_member=$(grep "${final_set};${final_member}" ${overviewfile} | awk -F ';' "NR==${i} {print \$$(echo ${col_orig_member})}")   
         orig_dir=/tank/exports/ERC_PALAEO/${orig_set}/${orig_member}/scripts

         outdir=${outdir_base}/set_${final_set}/original_runscripts

         if [ ! -d ${outdir} ]; then mkdir -p ${outdir};  fi # outdir exists?

         cd ${orig_dir}

         tar -cvf ${orig_member}_scripts.tar * && rm -f ${orig_member}.job{1,2,3} ${orig_member}.run safe_copy.bash monitoring.bash plot_monitoring.bash rerun_postpro.bash pert_list.dat
         mv -n ${orig_member}_scripts.tar ${outdir}

      done # i 

   done # final_member

done # final_set

exit 0
