#!/bin/bash

# This scripts takes 2 or 3 arguments:
#    Param 1: Name of "source" directory (where good data is located)
#    Param 2: Name of "dest" directory (where to save a copy of the data)
#    Param 3: Optional name of "change" file (list of files to be saved)
#	      If not present the scripts looks for 'chg.lst' in current dir
usage() {
echo "Usage: savefiles {source directory} {destination directory} [filename]"
exit 1
}

# Validate the caller's parameters
if [ ${#*} -lt 2 ]; then
  usage
fi
if [ ! -d $1 ]; then
  echo "Cannot find directory '$1'"
  usage
fi
if [ ! -d $2 ]; then
  echo "Cannot fine directory '$2'"
  usage
fi
if [ ${#*} -gt 2 ]; then
  d=$3
else
  d=./chg.lst
fi
if [ ! -f $d ]; then
  echo "Cannot find file '$d'"
  usage
fi

# Read in the list of files to be saved
a=$(< $d)
# Iterate through the list
for f in $a; do
  # Make sure the requested file is present in source directory
  if [ ! -e $1/$f ]; then
    echo "Cant find '$f' in $1"
  else
    # If directory not present in destination directory, create it
    dir=`dirname $f`
    if [ ! -d $2/$dir ]; then
      echo "Creating directory '$dir' in $2"
      mkdir -p $2/$dir
    fi
    # Then copy in the file
    cp -a $1/$f $2/$f
  fi
done
