#!/bin/ksh
#
#@ shell            = /usr/bin/ksh
#@ class            = ns
#@ job_type         = serial
#@ job_name         = prepare_atm_nudging
#@ output           = $(job_name).$(jobid).log
#@ error            = $(job_name).$(jobid).log
#@ notification     = error
#@ resources        = ConsumableCpus(1) ConsumableMemory(1200mb)
#@ wall_clock_limit = 48:00:00
#@ queue
#

set -xuve
date
tar="/opt/freeware/bin/tar"

grid=T255L91
expid=b0ir
mem=fc0
src=ec:/xes/public/longrange/$expid
dst=ec:/c3m/nudging/atmos/$grid/$expid

cup=$(pwd)
list=$cup/$expid

# Gather the list of original atm nudging ref. files
if [[ ! -a ${list} ]]; then
 emkdir -p $dst
 els -1 $src/* | cut -d '_' -f 4 | cut -c 1-6 | uniq >> $list
fi

tmp=$TMPDIR/prepare_atm_nudging_$expid
rm -rf $tmp
mkdir -p $tmp
cd $tmp

# Prepare and store the nudging ref. files after reformatting properly: e.g star with b0ir_reference_fc0_201003mmdd_1.tar and end up b0ir_fc0_201003.tar.gz
for l in $(cat $list); do
 rm -rf final; mkdir final
 ff=${expid}_${mem}_${l}.tar.gz
 ecp "$src/${expid}_reference_${mem}_${l}*" .
 for f in $(ls -1 ${expid}_reference_${mem}_${l}* | cut -d '.' -f 1); do
  nf=$(echo $f | cut -d '_' -f 4)
  $tar -xvf $f.tar
  mv $f/sh* final/${nf}sh
  mv $f/gg* final/${nf}gg
 done
 cd final
 $tar -cvzf ../$ff *${l}*
 emv ../$ff $dst
 cd ..
 rm -rf *_reference_*
 cat ${list} | sed -e '1d' > ${list}.tmp
 mv ${list}.tmp ${list}
done
rm ${list}
cd; rm -rf $tmp

date

