#! /bin/bash
cyflexlogevent -t generic -m 1 -m "script" -m "$0" 

# Script name: msu_files
#
# Purpose: Query the MSU database for this site and test cell and
#    generate the MSU files used by MSU command line programs.
#
# Usage:
#    msu_files TARGET_DIRECTORY
#
# TARGET_DIRECTORY is the directory where the generated files will be
#    created.  If omitted the directory the command is being run from
#    will be used.
#
# History:
#   08/07/2015 - Rob Janes - Initial release
#

# Check the target directory if specified to insure it's an existing
# directory.
if (( $# == 0 )); then
   # No command line argument, default to the current directory.
   TARGET_DIRECTORY=.
else
   if [ ! -d $1 ]; then
      echo $1 must be an existing directory.
      exit 1
   fi
   TARGET_DIRECTORY=$1
fi

# Determine the database to query.  Sets $DB.
. find_database.sh

# Insure the database is up and running.
DB=${DB:17:200}
db_check -database_url=$DB -username=readonly -password=5A+uWvIYLRL8tS68PmxDdg== -wait_period=30
if (( $?  != 0  )) ; then
   exit
fi

# Actually run the program to generate the files.
generic_java com.cybermetrix.cyflex.cui.msu.MSUFiles $*
if (( $? != 0 )) ; then
   echo Files not updated due to error or errors above.
   exit 1
fi

# Now make sure all the files of interest got generated.
typeset int OK=0
for NAME in msu_cell.arr  msu_pri.arr  program_grp  state_codes  test_type  vpi_phase; do
   FILE=$TARGET_DIRECTORY/$NAME
   if [ ! -e $FILE ]; then
      OK=1
      echo $FILE did not get generated.
   fi
done
if (( $OK != 0 )); then
   echo Files not updated due to error or errors above.
   exit 1
fi

# Actually install updated files.
cp test_type    /data
cp vpi_phase    /data
cp program_grp  /data
cp state_codes  /data
cp msu_cell.arr /specs
cp msu_pri.arr  /specs
