#!/bin/sh
#
# NAME
#   makeDist: make distribution for this software project
#
#
# USAGE
#   MD/bin/makeDist
#
#   (Must run in the base directory of the PST distribution.)
#
#
# DESCRIPTION
#   Instructions:
#
#     () Make your working directory the "root" directory of the PST
#        heirarchy.
#
#     () Make sure no distribution or backup already exist for the
#        current day.  If it does, then this script will fail and tell
#        you to remove those directories.  This is intentional because
#        it requires some thought before overwriting an existing
#        distribution or backup directory or file.
#
#     () Type "MD/bin/makeDist".
#
#        This will create a directory called PST-YYYYmmmDD where
#        YYYYmmmDD is a timestamp string using obvious notation.
#        This directory will not contain any of the CVS directories.
#
#        This will also create a ".tar.gz" file of that directory.




# TAR_FLAGS: list of flags for creating a distribution
#
# GNU: h follows symbolic links
#
# IRIX: L follows symbolic links.
#       K tars files greater than 2 gigabytes.

TAR_FLAGS=cf

# DIST: list of entries to put in this distribution.
DIST="MD SET TUSC sums"




#BACKUP_DIR=`date +%Y%b%d | tr '[A-Z]' '[a-z]'`
BACKUP_DIR=$1
DIST_DIR=PST-${BACKUP_DIR}
DIST_FILE=${DIST_DIR}.tar




# makeSums: create checksum files to determine integrity of files
makeSums ()
{

  if [ -f sums ]; then
    rm sums
  fi
  find . -type f -exec sum {} \; \
    | sort -n                    \
    > sums
}




# makeTarfileByDate: create tar file named by current date
makeTarfileByDate ()
{
  makeSums

  for item in $DIST ; do
    if [ ! -e $item ]; then
      echo "makeTarfileByDate: ERROR: could not find '$item' here."
      echo "  You probably ran makeDist from the wrong directory."
      echo "  Run from the root directory of this distribution."
      exit 1
    fi
  done

  if [ -d "$BACKUP_DIR" ]; then
    echo "makeTarfileByDate: ERROR: directory '$BACKUP_DIR' already exists."
    echo "  Remove that directory to make a new tarfile."
    exit 2
  else
    mkdir $BACKUP_DIR
  fi

  tar ${TAR_FLAGS} ${BACKUP_DIR}/${DIST_FILE} ${DIST}
}




# makeBackupByDate: make directory, named by date, containing backup
makeBackupByDate ()
{
  makeTarfileByDate

  (
    cd $BACKUP_DIR                     ;
    tar xf $DIST_FILE && rm $DIST_FILE ;
    find . -type d -name 'CVS' -exec rm -r {} \;
  )
}



# makeDistByDate: make distribution file, named by date
makeDistByDate ()
{
  makeBackupByDate

  if [ -d "$DIST_DIR" ]; then
    echo "makeDistByDate: ERROR: directory '$DIST_DIR' already exists."
    echo "  Remove that directory to make a new tarfile."
    echo "  Remove '$BACKUP_DIR' too."
    exit 4
  fi

  mv $BACKUP_DIR $DIST_DIR
  tar $TAR_FLAGS $DIST_FILE $DIST_DIR
  gzip $DIST_FILE
}




makeDistByDate
