#!/bin/sh
#
# Database Creation - IBM WebServices Gateway
#
# The arguments are:
# "1: WebSphere AppServer Directory"
# "2: DB2 instance owner ID"

#---- Function definitions

# Function to do cleanup on temporary files
fCleanup()
{
  rm -f "${tmpDBScript}"
  rm -f "${tmpSqlFile}"
}

# A function to terminate the execution of the script due to an error.
# Arguments may be supplied, which will each be printed to a new line on
# standard error.
fErrorExit()
{
  while [ $# -gt 0 ]; do
    echo "$1" >&2
    shift
  done
  echo >&2
  echo 'The WebServices Gateway database has NOT been created.' >&2
  echo >&2

  fCleanup

  exit 1
}

#---- Start of script execution

cd `dirname "$0"`

progName=`basename "$0"`
progDir=`pwd`

# Check we are the root user or things may not work
userName=`id | sed 's/[^(]*(\([^)]*\).*/\1/'`
[ "${userName}" = 'root' ] || fErrorExit \
  "You must be the 'root' user to run ${progName}." \
  "You are currently logged in as ${userName}."

# Test there are the correct number of arguments (extra args are ignored)
[ $# -ge 2 ] || fErrorExit \
  "${progName} requires the following arguments:" \
  '  1: WebSphere AppServer Directory (no trailing /)' \
  '  2: DB2 instance owner ID' \
  "Example: ./${progName} /opt/WebSphere/AppServer db2inst1"

wasDir="$1"
db2user="$2"
logFile="${wasDir}/logs/WSGWinstallDB.log"
tmpDir="${TMP:-/tmp}"
dbScript='installDB.sh'
dbName='wsgwdb'
sqlFile='WSGWDB.sql'
tmpDBScript="${tmpDir}/${dbScript}"
tmpSqlFile="${tmpDir}/${sqlFile}"

# Test the WAS directory exists
[ -d "${wasDir}" ] || fErrorExit \
  'The directory specified for WebSphere AppServer does not exist:' \
  "  ${wasDir}"

# Copy the script to be run and it's associated SQL file into a location
# where it can be accessed by the DB2 userid
cp -f "${progDir}/${dbScript}" "${tmpDBScript}"
chmod a+rx "${tmpDBScript}"
cp -f "${progDir}/${sqlFile}" "${tmpSqlFile}"
chmod a+r "${tmpSqlFile}"

echo 'Creating the WebServices Gateway database. This may take some time...'

# Invoke the database creation script as the DB2 instance ID
su - ${db2user} -c "${tmpDBScript} ${dbName} ${tmpSqlFile}" \
  > "${logFile}" 2>&1 || fErrorExit \
  'Database creation failed. Try looking at the WSGWInstallDB.log file in the' \
  '/logs subdirectory of the WebSphere AppServer dir to diagnose the problem.'

# Just in case the exit status from the 'su -c' command isn't the exit status
# of the specified command, check the output log for the success message
(tail -1 "${logFile}" | grep '^WSGW database creation successful$') \
  > /dev/null 2>&1 || fErrorExit \
  'Database creation failed. Try looking at the WSGWInstallDB.log file in the' \
  '/logs subdirectory of the WebSphere AppServer dir to diagnose the problem.'

echo 'The WebServices Gateway database has been successfully created.'
fCleanup
exit 0
