#!/bin/bash
###############################################################################
#PROGRAM: repack.sh
#WRITTEN BY: Stephen Saleeby
#PURPOSE: This script repacks hdf5 files to a certain compression level 1-9.
# We typically use level 6, so this is default below. This script works by
# taking in 3 custom things below that include (1) filepath to the directory
# that contains files you want to compress, (2) compression level, (3) the 
# prefix for you analysis files. The script runs "h5dump" on each file found 
# in the given directory, sends the output to a temporary file, reads the 
# temp file to search for key words that tell the compression level. If the 
# current compression level does not match your chosen level, then compression 
# occurs. Repack creates a new compressed file with a temporary name and then 
# overwrites the original file with the newly compressed file.
###############################################################################

#THREE PARAMETERS FOR USER TO SET

#FILEPATH
fp=zzz.test.6.1.18.halifax_dm/z.test.storm0
fp=.
#REPACK EXECUTABLE PATH
h5rp="/p/home/smsaleeb/rams_20170320_dev/misc/hdf5-1.8.9/bin"
h5rp=.
#COMPRESSION LEVEL
compresslev=6
#ANALYSIS FILE PREFIX
pre="a-A-"

###############################################################################
############### COMPRESSION SCRIPT ############################################
###############################################################################
for f in $fp/$pre*.h5; do

 level=$compresslev
 file=$f
 newfile=$f".1"
 h5dump -p -d /GLAT -s "0" -c "0" $file > ./pack.txt
 
 ncount=0
 while read var1 var2 var3 var4 var5 var6 var7 var8 var9
 do
   if [ "$var1" == "FILTERS" ]; then 
     ncount=1; 
   fi;
   if [ $ncount -eq 1 ] && [ "$var1" == "NONE" ]; then
     level=$var1
     echo "File: $file"
     echo "Old compress level= $level, New compress level= $compresslev"
     $h5rp/h5repack -f SHUF -f GZIP=$compresslev $file $newfile
     mv $newfile $file
     break
   fi
   if [ $ncount -eq 1 ] && [ "$var1" == "PREPROCESSING" ]; then
     ncount=2;
   fi
   if [ $ncount -eq 2 ] && [ "$var1" == "COMPRESSION" ]; then
     level=$var5
     echo "File: $file"
     echo "File compression level = $level"
     if [ $level -ne $compresslev ]; then
      echo "Old compress level= $level, New compress level= $compresslev"
      $h5rp/h5repack -f SHUF -f GZIP=$compresslev $file $newfile
      mv $newfile $file
     fi
     break
   fi
 done < ./pack.txt
 rm -f ./pack.txt

done
###############################################################################
