#!/bin/sh 
#
#  The passed in file, contains 1 or more lines each of which is the name of a file
#  Read in the contents of the passed in file and construct another file that is the union of the
#  files mentioned in the passed in file.
#
set -u  # force better programming and ability to use check for not set
if [ "${1:-}" = "-x" ] ; then set -xv; shift; fi

print_error() {
   echo " "
   echo "$1"
   echo " "
}

DEFAULT_OUTPUT_DIR=/fnal/ups/prd/www_pages/enstore

if [ $# != 1 ] && [ $# != 2 ];
then
   # we need the name of the file listing the files to include
   print_error "USAGE: $0 [-x] <filename> [output_dir (D:${DEFAULT_OUTPUT_DIR})]"
   exit 1
fi

if [ "${ENSTORE_DIR:-x}" = "x" ];
then
    set +u
    if [ -f /fnal/ups/etc/setups.sh ];
    then
       . /fnal/ups/etc/setups.sh
       setup enstore
    elif [ -f /usr/local/etc/setups.sh ];
    then
       . /fnal/ups/etc/setups.sh
       setup enstore
    else
       print_error "ERROR: Cannot find UPS to setup enstore, set it up first."
    fi
    set -u
fi

if [ -f $1 ];
then
  # $2 is the directory that we will use to create the new file.
  # default is /fnal/ups/prd/www_pages/enstore
  if [ "$#" = "2" ];
  then
    output_dir=$2
  else
    output_dir=$DEFAULT_OUTPUT_DIR
  fi

  real_output=${output_dir}/enstore_system.html
  tmp_output=${real_output}.tmp

  # get rid of any old enstore_system.html's in this directory
  rm -f $tmp_output
  # start out with an empty file
  touch $tmp_output
  # now fill the file
  for file in `cat $1`;
  do
    eval "if [ -e $file ]; then cat $file >> $tmp_output; fi"
  done
  # now create the real file
  mv $tmp_output $real_output
else
  print_error "ERROR: entered file does not exist or is not a normal file."
  exit 1
fi
