# Collect files and create a support bundle

if [ "$EUID" -ne 0 ]
  then echo "Support Bundle script is not started by root" >> /var/log/usgmtr/um.log
  exit 1
fi

source `dirname $0`/../umsetenv.sh
tmp='/tmp'
genDT=`date +"%Y-%m-%d-%H-%M-%S"`
filename="um-support-"$genDT
fullpath=$tmp/$filename

# Remove any previous log bundles
rm -f /tmp/um-support-*.tgz

# Make a directory to store the logs
mkdir $fullpath 2>/dev/null

# Copy the UM logs into a dedicated folder
ubak="$fullpath/um"
um_log_path="/var/log/usgmtr/"
mkdir $ubak
cp -rv $um_log_path $ubak

# Copy the PostgreSQL files into a dedicated folder
dbbak="$fullpath/db"
mkdir $dbbak
cp -v /var/vmware/vpostgres/current/pgdata/postgresql.conf $dbbak
cp -rv /var/vmware/vpostgres/current/pgdata/pg_log $dbbak

# Back up any particular web files that we may want to look at
webbak="$fullpath/web"
mkdir $webbak
webconf="$TOMCAT_HOME/conf/web.xml"
weblog="$TOMCAT_HOME/logs"
cp -v $webconf $webbak
cp -rv $weblog $webbak

# Copy /var/log/messages
varlog="$fullpath/var/log/"
mkdir -p $varlog
cp -v /var/log/messages $varlog

webappSupportDir="$TOMCAT_HOME/webapps/um/bundleDir"

# Create webappSupportDir if does not exist
if [ ! -d "$webappSupportDir" ]; then
  mkdir $webappSupportDir
fi

pushd $tmp > /dev/null
tar -pczf $webappSupportDir/$filename.tgz $filename

# Check if tar command was successful and print file location
if [ $? -eq 0 ]; then
  echo "Support bundle created: $webappSupportDir/$filename.tgz"
fi

# Set owner and permissions (even if the dir already existed, because they may be wrong)
chown -R usgmtr $webappSupportDir
chmod -R 700 $webappSupportDir

# Purge the temporary directory, since we have a tarball of the logs & data
rm -rf $fullpath

popd > /dev/null

# Return 0 if bundle file exists
if [ -f "$webappSupportDir/$filename.tgz" ]; then
  exit 0
else
  exit 1
fi
