#!/bin/bash

# Archives a simulation's output and input as a "keeper" under a user-defined name.
# It moves all output files and copies selected input files to a user-defined new directory in the ELM_ARCHIVE_PATH.
# This can be used as either as a stand-alone or as a call from other scripts such as "Run".

# 1) The script establishes paths and environment variables, calling a few scripts, 
# 2) establishes a directory structure based on the name given to the model run,
# 3) moves (not copies) model output with new run-name suffixes to the new directories,
# 4) copies selected (most likely to be changing) input data and source files (w/ new suffixes),
# 5) and, for subsequent model runs, calls the mkOutDirs script to re-create any needed directories.

# Calls the following ELM scripts:
# PathELM_HOME, PathModel, PathOutput, PathArchive, mkOutDirs

# As with all ELM scripts, stay with Bourne shell (/bin/sh) for universal application.
# 	Note: for getting a variable from a child shellcommand, ". shellcommand" does similar/same thing 
# 	as "source shellcommand" (latter didn't work in Sun solaris implmentation)

# TO DO 
# May 2004: for better portability, fix the substitutions used in pattern matching etc and use sh
# the temporary fix is to just use #!/bin/bash here instead of #!/bin/sh
#


echo "Archiving model output and selected input..."

# *******************
# take care of environment variables and paths
# *******************

####
#### ELM_HOME Path
# determines if the (fundamental) ELM_HOME environment variable appears valid
PathELM_HOME

if test $# != 2
then
    echo "###### Error:  you must supply 1) an existing ProjectName "
    echo "and 2) a new descriptive suffix to designate the run. "
    echo "(example: ArchiveRun ELM myFirstRun)"
    exit
fi


####
#### Model Path
# establish the ModelPath for the model Project data/executable from the PathModel script
. PathModel

####
#### Driver Path
DriverPath=$ELM_HOME/SME/SMDriver/
export DriverPath

####
#### Project Name
ProjName=$1
export ProjName

####
#### Run Name
RunName=$2
export RunName

####
#### Output Path
# establish the output path for model results from PathOutput script
. PathOutput $ProjName 

####
#### Archive Path
# establish the path for archiving the model from PathArchive script
. PathArchive

############
#IMPORTANT: ensure that there is not another archived run with same name (that will be overwritten)
############
if test -d $ELM_ARCHIVE_PATH/$ProjName/$RunName
  then
    echo "###### Error:  That output run name exists in the archive - use another run name suffix."
    echo "Existing archive: $ELM_ARCHIVE_PATH/$ProjName/$RunName"
    exit
  else
    # always will be a new directory (have checked above for pre-existing)
    mkdir $ELM_ARCHIVE_PATH/$ProjName/$RunName
fi


##########
# establish directory structure
##########
##########
# move the Animation time series output files
##########
# create directories for animations in the
# user defined run directory.
# append the run name specified by the user to 
# the animation file names (without the extensions) 
# and move them to the  new animation directories.  
# first move the spatial time series files

echo "Moving spatial time series output files..."
for dirnam in `ls -d $OutputPath/$ProjName/Output/Animation*`   
  do
    # Note: don't use ls -f $dirnam/* -- does not work in solaris
    # the way is expected. Also, test -f $dirnam/* does not work in
    # GNU bash, version 2.03.0(1)-release (sparc-sun-solaris)
    for name in `ls $dirnam/`
    do
      #with everything, up to and including last / stripped out
	  # the " f=${name##*/} " has "bad substitution" error in sun solaris sh - using bash temporarily
      f=${name##*/}
      #all matches of pattern[0-9] in f is replaced by null
      ff=${f//[0-9]/}
	  echo $ff
      # we care only about one file, because all of them
      # start with the same name. This name is used for
      # renaming the Animation* directory.
      new_dir=$ELM_ARCHIVE_PATH/$ProjName/$RunName/$ff.$RunName
      mv $dirnam $new_dir
      break
    done
  done

##########
# move canal, budget/IR, and debug time series output files
##########
# move the canal-related output files
# move the budget-related (incl. IRavg) output files
# move the debug-related output files
# Note: Animation stuff must be moved first!
# Note: Add any new directories that are located in $OutputPath/$ProjName
#       to this list.
echo "Moving canal, budget/IR, and debug time series output files..."

dirs="Canal Budget Debug"
for d in $dirs
do
  old_dir=$OutputPath$ProjName/Output/$d
  # this if is not working !
  #if test -f $OutputPath$ProjName/$d/* 
  #then
    new_dir=$ELM_ARCHIVE_PATH/$ProjName/$RunName/$d
    mkdir $new_dir
    for name in `ls $old_dir/*`
    do
      f=${name##*/}
      mv $name $new_dir/$f.$RunName   
    done
  #fi
done

##########
# move the Point(cell) time series output files
##########
# must process the PtSer file independently
# must add a '1' to the file name and must get rid of
# pts extenssion
# move the point time series output files
echo "Moving Point(cell) time series output files..."

dirs="PtSer"
for d in $dirs
do
  old_dir=$OutputPath$ProjName/Output/$d
  # this if is not working !
  #if test -f $OutputPath$ProjName/$d/* 
  #then
    new_dir=$ELM_ARCHIVE_PATH/$ProjName/$RunName/$d
    mkdir $new_dir
    for name in `ls $old_dir/*.pts`
    do
      f=${name##*/}
      mv $name $new_dir/$f.$RunName   
    done
  #fi
done

##########
# copy/move the selected input data and source files
##########
new_dir=$ELM_ARCHIVE_PATH/$ProjName/$RunName/Input
mkdir $new_dir
echo "Copying selected input and source code files..."

# Notes: move the notes on the simulation 
mv $OutputPath/$ProjName/Output/Notes.$RunName $ELM_ARCHIVE_PATH/$ProjName/$RunName/Notes.$RunName

# Input data
# a duplicate copy of particular (frequently changing) data files is made
# at runtime if model executed via Run script - this duplicate is appended with the runName,
# so the original may be modified by other projects while a run is being made

# move all data files that were copied to name.RunName at start of simulation using "Run" script 
mv $ModelPath$ProjName/Data/*.$RunName $ELM_ARCHIVE_PATH/$ProjName/$RunName/Input/

# move Driver.parm and Model.outList files that were copied to name.RunName at start of simulation using "Run" script 
mv $ModelPath$ProjName/RunParms/*.$RunName $ELM_ARCHIVE_PATH/$ProjName/$RunName/Input/

# Source code
# copy some of the source files with dynamic calculations 
# (just for model development periods when fooling with code a lot)
#cp -p $DriverPath/Sources/UnitMod/UnitMod.c $ELM_ARCHIVE_PATH$ProjName/$RunName/Input/UnitMod.$RunName.c
#cp -p $DriverPath/Sources/SpatMod/WatMgmt.c $ELM_ARCHIVE_PATH$ProjName/$RunName/Input/WatMgmt.$RunName.c
#cp -p $DriverPath/Sources/SpatMod/Fluxes.c $ELM_ARCHIVE_PATH$ProjName/$RunName/Input/Fluxes.$RunName.c


##########
# done with archiving
##########
echo "Archived run from $OutputPath/$ProjName/Output/ to $ELM_ARCHIVE_PATH/$ProjName/$RunName"

# create the project output directory names if needed by calling mkOutDirs script
# (the Animation* directories that had output need re-creating after ArchiveRun is run)
mkOutDirs $OutputPath $ProjName
