#!/bin/sh
################################################################3
#
#  This script will tar up the directory specified by the first
#  argument ($1) and place the tar file on the com place for ncos70as,
#  under /hsmuser/climprod.  The tar file is put in the directory
#  appropriate for data valid for the day specified as the second 
#  command line argument ($2).
#
#  Also a list of the files in the tar file is placed in a corresponding
#  directory in /clim/cpccom/output. If this inventory list already exists,
#  it is assumed that the directory has already been saved, and this 
#  script exits with return code 0.
#
#  Usage: savedir.sh Directory Date(YYYYMMDDHH format)
#
#  Where: Directory  = Directory to be tarred.
#         Date = YYYY/YYYYMM that the tar file should be saved under.
#
################################################################3
set -x

if [ $# -ne 4 ]
then
  echo "Usage: savedir.sh Directory Date(YYYYMMDD format)"
  exit 1
fi 

#
#   Get directory to be tarred from the first command line argument,
#   and check to make sure that the directory exists.
#

dir=$1
ymdh=$2
tardir=$3
member=$4
if [ ! -d $dir ]
then
  echo " Directory $dir does not exist."
  exit 2
fi 

if [ $member -lt 10 ]; then member=0$member; fi
#
#   cd to the directory to be tarred.
# 

cd $dir/$ymdh

#
#   Generate the name of the tarfile, which should be the same
#   as the absolute path name of the directory being
#   tarred, except that "/" are replaced with "_".
#

#tarfile=`echo $PWD | cut -c 27 | tr "/" "_"`
#tarfile=`echo $PWD | cut -c 27-34` 
if [ $RUN = foreavrg ]
then
    tarfile=forecast
else
    tarfile=hindcast
fi

tarfile=${tarfile}_$ymdh.tar

#
#   Determine the directory where the inventory lists of the tarred 
#   files will be stored and make sure that it exists.
#

year=`echo $ymdh | cut -c 1-4`
yearmo=`echo $ymdh | cut -c 1-6`
listdir=$DATA

#
#   Tar up the directory and put the tarred file in the 
#   appropriate directory for tranfer to hsm
#  

date
tar -cf $tardir/$tarfile *

cd $dir
tar -rf $tardir/$tarfile flx$member.* pgb$member.* extvars$member.*
err=$?
if [ $err -ne 0 ]
then
  echo " Directory $dir/$ymdh was not successfully tarred."
  exit 3
fi 
date

#
#   Read the tarfile and save a list of files that are in the tar file.
# 

tar -tf $tardir/$tarfile > $listdir/${tarfile}list
err=$?
if [ $err -ne 0 ]
then
  echo " Tar file $tarfile was not successfully read to"
  echo " generate a list of the files."
  exit 4
fi 

chmod 775 $tardir/$tarfile
