#!/bin/bash
# Bill Barrett Feb 2020

# Seasons to be processed
declare -a seasons=("north" "south")
# Years to be processed
declare -a years=("07" "08" "09" "10" "11" "12" "13" "14" "15" "16" "17" "18")
#declare -a years=("07")
# Levels to be processed
declare -a levels=("2a" "2b")

for season in "${seasons[@]}"; do
  for year in "${years[@]}"; do
    seasonYear="${season}_20${year}"
    # north_2014 is the only possible combination of season and year
    #  that should be excluded
    for level in "${levels[@]}"; do
      sourceDir="/aim/data/cips/${seasonYear}/raa/level_${level}/ver_01.10/rev_04/"
      echo $sourceDir
      # It is meaningful to continue only if the source directory exists
      if [ -d "$sourceDir" ]; then
        echo "${sourceDir} exists"
        # The new directory is the same other than rev_04 => rev_05
        destDir=${sourceDir//rev_04/rev_05}
        echo $destDir
        # Create the directory ignoring the error if it already exists
        # Make the directory universally readable and executable (for Windows access)
        mkdir -p -m 755 $destDir
        # First copy the files ensuring that the attributes are preserved and that
        #   the owner is "aimpro"
        for file in "$sourceDir"/*; do
          echo $file
          mv -v $file $destDir
        done
        # Then rename the destination files from r04 => r05
       for file in "$destDir"/*; do
          if [ -f "${file}" ] ; then
            mv -v $file "${file//_r04/_r05}"
          else for sfile in "${destDir}/${file}/*"; do
            mv -v $sfile "${sfile//_r04/_r05}"
          done
          fi
       done
      fi
    done
  done
done

