#!/bin/bash
# IBM Confidential
# OCO Source Materials
# 5724-V51
#
# (c) Copyright IBM Corp. 2000, 2008 All Rights Reserved.
#
# The source code for this program is not published or otherwise
# divested of its trade secrets, irrespective of what has been
# deposited with the U.S. Copyright Office.

# This is the main driver script for Diagnostic Tools
# It mostly interpret command line options, and redirect to corresponding
# sub-scripts for the actual processing.
#
# To see the usage information: 
# pimSupport.sh --help 
#                    

# if TOP is not set in the environment, take the first argument as the TOP dir
# This is for the invocation from ISA to this script, where TOP env is not available
if [ "X${TOP}" == "X" ]; then
    export TOP=$1
    echo "Setting TOP to $TOP"
    # source $TOP/bin/diagnostic/env_setup.rc
    . $TOP/bin/diagnostic/env_setup.rc 2>&1 > /dev/null
fi


. ${TOP}/bin/get_params.sh

# variables used by this script
#
WPCSUPPORTDIR=""
TIMESTAMP=$(/bin/date +%m%d%Y_%H%M%S)
#TIMESTAMP=`$JAVA_RT com.ibm.ccd.common.wpcsupport.util.SupportUtil --cmd=getTimeStamp`
WPCSUPPORT="pimSupport"
DBDIR="dblogs"
DB2SUPPORT="db2support"
APPSRVR="ApplicationServer"
APPSRVRLOGS="Logs"
SYSINFODIR="syslogs"
MONITORINFODIR="monitorlogs"
HIGHCPUDIR="highcpulogs"
UNDERSCORE="_"
CURRENTEXECDIR=`pwd`
TOPBINDIR=$TOP/bin
SAVEDDIR=$CURRENTEXECDIR

# ensure the correct directory
if [ "$CURRENTEXECDIR" != "$TOP/bin" ]; then
    # echo "Please execute pimSupport.sh under $TOP/bin directory"
    cd $TOPBINDIR
    CURRENTEXECDIR=`pwd`
fi

# source all the functions to be used:
. $TOP/bin/diagnostic/common/common.functions
. $TOP/bin/diagnostic/pim_support/pimSupport.functions


if [ $# == 0 ]; then
    cat $TOP/bin/diagnostic/pim_support/pimSupport.version
    echo ""
    echo "For script usage, type: pimSupport.sh --help" 
    echo ""
    exit 0
fi

for _VAR in "$@"; do
    case ${_VAR} in
        --help)
        cat $TOP/bin/diagnostic/pim_support/pimSupport.usage
        exit 0
    esac
    case ${_VAR} in
        --version)
        cat $TOP/bin/diagnostic/pim_support/pimSupport.version
        exit 0
    esac
done

# For option: monitor=[start|stop], we need to move from pimSupport_localized.sh to here
# because pimSupport_localized.sh is executed within a Java process, and it has problems 
# returning from background job.
#
# start background system monitoring
if [ "X${_CCD_MONITOR}" != "X" ]; then

    if [ "$_CCD_MONITOR" = "start" ]; then
        ${ECHO} Starting system status monitor in background
        STATUS_DIR=$TOP/logs/diagnostic/system_status
        mkdir -p $STATUS_DIR

        $TOP/bin/diagnostic/common/startMonitor.sh &

        echo $! > $STATUS_DIR/monitor.pid 
	${ECHO} Saved background PID=`cat $STATUS_DIR/monitor.pid` 

        exit 0
    fi
    if [ "$_CCD_MONITOR" = "stop" ]; then
        ${ECHO} Stopping the background system status monitor

        $TOP/bin/diagnostic/common/stopMonitor.sh 
        exit 0
    fi

    echo "Option usage: --monitor=[start|stop]"
    exit 1
fi

# if integrity check, forward it to corresponding script
if [ "X${_CCD_INTEGRITY}" != "X" ]; then
        echo "[pimSupport.sh] command line: $@"

	# we have to pass along the catalog/colarea name with space in it, such as "Product Catalog"
	# encoded it using ~ to replace the space
	if [ "X${_CCD_CATALOG}" != "X" ]; then
		export OPT_CATALOG=`echo ${_CCD_CATALOG} | sed 's/ /~/g'`
	fi

	if [ "X${_CCD_COLAREA}" != "X" ]; then
		export OPT_COLAREA=`echo ${_CCD_COLAREA} | sed 's/ /~/g'`
	fi

        $TOP/bin/diagnostic/integrity_check/integrityCheck.sh $@

    exit 0
fi

# if health check, forward it to healthCheck.sh
if [ "X${_CCD_HEALTH}" != "X" ]; then
	$TOP/bin/diagnostic/health_check/healthCheck.sh $@
	exit 0
fi

# It seems that there is issues that calling to the localized script, to produce output from WPCSupport.java;
# so we make the shell script version here for now.
# all functionality from pimSupport_localized.sh is moved to this file below
#
# $JAVA_RT com.ibm.ccd.common.db.LocalizedShellScriptRunner "${SHELL} pimSupport_localized.sh $*" "$TOP/bin"
#

# set the output directory as specified
if [ "X${_CCD_OUTPUTDIRECTORY}" != "X" ]; then
    if [ ! -e ${_CCD_OUTPUTDIRECTORY} ]; then
        ${ECHO} COMMON_ERROR_INVALID_DIR_SH ${_CCD_OUTPUTDIRECTORY}
        exit 5
    fi
    if [ ! -d ${_CCD_OUTPUTDIRECTORY} ]; then
        ${ECHO} COMMON_ERROR_NOT_DIR_SH ${_CCD_OUTPUTDIRECTORY}
        exit 5
    fi
    if [ ! -w ${_CCD_OUTPUTDIRECTORY} ]; then
        ${ECHO} COMMON_ERROR_NO_WRITE_PERM_SH ${_CCD_OUTPUTDIRECTORY}
        exit 5
    fi

      #convert all the relative paths to absolute path
      cd ${_CCD_OUTPUTDIRECTORY}
      _CCD_OUTPUTDIRECTORY=`pwd`
      cd -
      WPCSUPPORTDIR=${_CCD_OUTPUTDIRECTORY}/
fi

# find the temp directory from common.properties, if not passed in argument list
if [  "X${_CCD_OUTPUTDIRECTORY}" = "X" ]; then
    # TMPDIR=`$JAVA_RT com.ibm.ccd.common.util.Configuration --cmd=tmpdir`
    TMPDIR=`grep tmp_dir $TOP/etc/default/common.properties | cut -d "=" -f2`
    if [ "$TMPDIR" = "" ]; then
        ${ECHO} COMMON_ERROR_INVALID_DIR_BOTH_SH
        exit 5
    else
        if [ ! -e ${TMPDIR} ]; then
            ${ECHO} COMMON_ERROR_INVALID_DIR_SH
            exit 5
        fi
        WPCSUPPORTDIR=${TMPDIR}

    fi
fi

# If we are here that means we have found out a directory where we can
# create a directory with a timestamp within that.
WORKDIR=${WPCSUPPORTDIR}$WPCSUPPORT$UNDERSCORE$TIMESTAMP
mkdir -p $WORKDIR


# For making version correlation between ISA plugin and WPC release, we will try to
# to report if a specific command-line options are available in pimSupport.sh or not.
# For example, if a user takes a newer version of ISA plugin to work with a older version
# of WPC release, and the ISA menu has new optoins that WPC pimSupport.sh does not know,
# we will report "Option not supported in this pimSupport.sh version".
OPTION_PROCESSED=false

# dump high-cpu process information
if [ "X${_CCD_DUMPPROCESS}" != "X" ]; then
    # mark command line option handled
    OPTION_PROCESSED=true

    # produce process dump in $TOP/logs/high_cpu
    # echo COMMON_INFO_COLLECT_INFO_SH "High-CPU Process Info log files ...... wait about 2 minutes!"
    $TOP/bin/diagnostic/common/dumpProcessInfo.sh ${_CCD_DUMPPROCESS}

    # copy dump files from $TOP/logs/high_cpu to $WORKDIR/$HIGHCPUDIR
    collectProcessInfo
fi


# collect system information
if [ "X${_CCD_COLLECTSYSINFO}" != "X" ]; then
    # mark command line option handled
    OPTION_PROCESSED=true

    if [ "$_CCD_COLLECTSYSINFO" = "yes" ]; then
        # produce system info output
        $TOP/bin/diagnostic/common/systemInfo.sh

        # copy dump files from $TOP/logs/diagnostic/env_info to $WORKDIR/$HIGHCPUDIR
        collectSysInfo
    fi
fi


# collect log files from background system monitoring
if [ "X${_CCD_COLLECTMONITORLOGS}" != "X" ]; then
    # mark command line option handled
    OPTION_PROCESSED=true

    if [ "$_CCD_COLLECTMONITORLOGS" = "yes" ]; then
        collectMonitorLogs
    fi
fi


# collect Database Infomation
if [ "X${_CCD_COLLECTDBINFO}" != "X" ]; then
    # mark command line option handled
    OPTION_PROCESSED=true

    if [ "$_CCD_COLLECTDBINFO" = "yes" ]; then
        collectDBLogs
    fi
fi


# Collect Application Server Logs ?
if [ "X${_CCD_COLLECTAPPSVRLOGS}" != "X" ]; then
    # mark command line option handled
    OPTION_PROCESSED=true

    if [ "$_CCD_COLLECTAPPSVRLOGS" = "yes" ]; then
        collectappsverlogs
    fi
fi


# collect WPC config properties files
if [ "X${_CCD_COLLECTWPCCONF}" != "X" ]; then
    # mark command line option handled
    OPTION_PROCESSED=true

    mkdir -p ${WORKDIR}/wpcconf
    cp -f $TOP/etc/default/*.xml ${WORKDIR}/wpcconf
    cp -f $TOP/etc/default/user_jars.list ${WORKDIR}/wpcconf
    if [ -f $TOP/setup/init_ccd_vars.sh ]; then 
        cp -f $TOP/setup/init_ccd_vars.sh ${WORKDIR}/wpcconf
    fi

    # we want to filter db_password
    grep -v db_password $TOP/etc/default/common.properties > ${WORKDIR}/wpcconf/common.properties
fi


# collect WPC service log files
if [ "X${_CCD_COLLECTWPCLOGS}" != "X" ]; then

    # mark command line option handled
    OPTION_PROCESSED=true

    # convert to lower case, so "aLL", "AppSvr" become "all", "appsvr"
    lowerValue=`${ECHO} ${_CCD_COLLECTWPCLOGS}| tr '[:upper:]' '[:lower:]'`

    OLDIFS="$IFS"
    IFS="|"
    arrOpts=( $lowerValue )
    IFS="$OLDIFS"

    count=0
    while [ $count -lt 6 ];
    do
        # echo "opt: ${arrOpts[$count]}"
        serviceName=${arrOpts[$count]} 

        if [ "${serviceName}" = "" ]; then
            # echo "no service name, skiping..."
            break
        elif [ "${serviceName}" = "all" ]; then
            # echo "copy all log files"
            cp -rf $TOP/logs/admin* ${WORKDIR}/wpclogs
            cp -rf $TOP/logs/appsvr* ${WORKDIR}/wpclogs
            cp -rf $TOP/logs/scheduler* ${WORKDIR}/wpclogs
            cp -rf $TOP/logs/workflowengine* ${WORKDIR}/wpclogs
            cp -rf $TOP/logs/queuemanager* ${WORKDIR}/wpclogs
            cp -rf $TOP/logs/eventprocessor* ${WORKDIR}/wpclogs
            break
        else
            # echo "copy one log file: $TOP/logs/${serviceName}* "
            cp -rf $TOP/logs/${serviceName}* ${WORKDIR}/wpclogs
        fi        

       count=`expr $count + 1`
    done 
fi


# the end... all options should have been handled above
#
if [ "$OPTION_PROCESSED" == "false" ]; then
        echo "-------------------------------------------------------------"
        echo "The option is not supported in this pimSupport.sh version, for command line: $@"
        cat $TOP/bin/diagnostic/pim_support/pimSupport.version
        echo "-------------------------------------------------------------"
        exit 2
fi

# when all is done, we can zip the "WORKDIR" folder into a zip file, and remove the folder
if [ -d ${WORKDIR} ]; then
	cd ${WORKDIR}
	# check if we have zip utility
	if [ "X`which gzip 2> /dev/null`" != "X" ]; then
		TARFILE=`basename ${WORKDIR}`
		cd ../
        	tar -cf ${TARFILE}.tar ${TARFILE}
		gzip ${TARFILE}.tar  
		cd ${CURRENTEXECDIR}
		rm -rf  ${WORKDIR}
		echo "All results can be found in ${WORKDIR}.tar.gz file"
	else
		echo "All results can be found under directory ${WORKDIR}"
	fi

fi

# go back to the original directory
cd $SAVEDDIR


exit 0
