#!/bin/ksh -p
#
#  explorer - System information data collector
#  $Id: //depot/stable/explorer/bin/explorer#4 $
#

# Put variable assignments in environment
set -ka

# Open up umask
umask 022

# Do not create core files
ulimit -c 0

# Remove /etc/opt/SUNWexplo/instinfo/install_info if it exists
if [ -f "/etc/opt/SUNWexplo/instinfo/install_info" ]
  then
    /usr/bin/rm -f /etc/opt/SUNWexplo/instinfo/install_info
    if [ "$?" -ne 0 ]
      then
        echo "Could not remove /etc/opt/SUNWexplo/instinfo/install_info"
        exit 1
      else
	echo "Removed file /etc/opt/SUNWexplo/instinfo/install_info"
    fi
fi

# Source main functions and parse arguments
DIR=`dirname $0`
if [ `echo ${DIR} | cut -c1` != "/" ]
then
    # Make DIR absolute path
    cd ${DIR}
    DIR=`pwd`
fi
MAIN="`dirname ${DIR}`/lib/exp_main"
if [ -f "${MAIN}" ]
then
    . ${MAIN}
elif [ -f "/usr/lib/explorer/exp_main" ]
then
    . /usr/lib/explorer/exp_main
else
    echo "Unable to source exp_main"
    exit 1
fi

# Clean up on any of the given signals
trap 'clean' 1 2 3 14 15

# Set PATH based on EXP_PATH
export PATH=${EXP_PATH}
export CLASSPATH=${EXP_HOME}/java/fruid-scappclient.jar:${EXP_HOME}/java/libfru.jar

export LD_LIBRARY_PATH=${EXP_LIB}
for lib in `echo ${EXP_PATH} | sed 's/:/ /g'`
do
    export LD_LIBRARY_PATH=`dirname ${lib}`/lib:${LD_LIBRARY_PATH}
done

# Validate defaults file
ksh -p ${EXP_LIB}/exp_check

# Just resend the latest explorer if told to.
if [ ! -z "${EXP_RESEND}" ]
then
   cd "${EXP_HOME}/output"
   EXP_TARGET=`ls -mt *.tar.gz`
   EXP_FILE=${EXP_TARGET}
   EXP_TARGET=${EXP_TARGET%.*}
   EXP_TARGET=${EXP_TARGET%.*}
   EXP_FNAME=`basename ${EXP_TARGET}`
echo "debug: EXP_TARGET=${EXP_TARGET}"
echo "debug: EXP_FNAME=${EXP_FNAME}"
echo "debug: EXP_FILE=${EXP_FILE}"
   TEXT=`gettext "resending the latest explorer: ${EXP_FILE}"`
   TEXT=`printf "${TEXT}" "${EXP_HOME}/output"`
   logfile NOTNOISE "${TEXT}"
   # Send the tarball
   if [ -n "${EXP_TRANSPORT}" ]
   then
       # Make sure EXP_REPLY is available to the transports
       ksh -p ${EXP_LIB}/exp_transport $*
   fi
   exit 0
else
# proceed as normal

# Check for Explorer already running
if [ -f /tmp/explorer_pid ]
then
  EXP_PID_CHECK=`cat /tmp/explorer_pid`
  EXP_PID_CHECK_COUNT=`ps -ef | grep ${EXP_PID_CHECK} |grep explorer |grep -v grep |wc -l`
  if [ ${EXP_PID_CHECK_COUNT} != 0 ]
  then
    echo "Explorer is already running. Exiting."
    echo "The PID of the explorer running is : ${EXP_PID_CHECK}"
    exit 1
  else
    echo "Explorer starting."
  fi
fi

# Set start time
EXP_START=`date -u '+%Y.%m.%d.%H.%M'`
EXP_PID="$$"

# Record this Explorer's PID for checking by submitted Explorers.
echo ${EXP_PID} > /tmp/explorer_pid

# Print some useful debugging info to log
logfile "EXP_HOME=${EXP_HOME}"
logfile "EXP_LIB=${EXP_LIB}"
logfile "EXP_DEFAULTS=${EXP_DEFAULTS}"
logfile "PATH=${PATH}"
logfile "LD_LIBRARY_PATH=${LD_LIBRARY_PATH}"
logfile "JAVA_HOME=${JAVA_HOME}"
logfile "CLASSPATH=${CLASSPATH}"

# Make sure EXP_ID is set
require 'test -n "${EXP_ID}"'
logfile NOTNOISE "explorer ID: ${EXP_ID}"
# logfile "local time: `date`"
TEXT=`gettext "local time: %s"`
date=`date`
TEXT=`printf "${TEXT}" "$date"`
logfile "${TEXT}"

# Must be Solaris 2.x and no previous EXP_TARGET
require "test `uname -s` = SunOS"
TEXT=`gettext "Must be run on SunOS 5.x"`
require "uname -r | grep '^5'" "${TEXT}"

require 'test -n "${EXP_TARGET}"'
TEXT=`gettext "EXP_TARGET=%s already exists"`
require 'test ! -d ${EXP_TARGET}' "${TEXT}"
require 'mkdir -p ${EXP_TARGET}'

# Redirect STDERR to stderr file above TARGET to allow for NFS collection
exec 2> ${EXP_STDERR:=${EXP_TMPDIR}/stderr.${EXP_PID}}

# Log to /var/adm/messages
TEXT=`gettext "Explorer started"`
logger -p daemon.notice -t explorer "${TEXT}"

#
#  DATA GATHERING
#

# Get current version of Explorer
EXP_CURRENT_VERSION=`echo ${EXP_VERSION} | cut -f1 -d,`

# Loop through all scripts
if [ "${EXP_HOME}" = "/" ]
then
    for script in ${EXP_LIB}/tools/*
    do
	if [ "${EXP_CURRENT_VERSION}" = "`egrep -e EXP_VERSION\= $script | cut -f2 -d=`" ]
	then
		ksh -p $script $*
	else
		[ ! -d "{EXP_TARGET}/${script##*/}" ] && { mkdir -p ${EXP_TARGET}/${script##*/}; }
		TEXT="\n Explorer module $script version is "`egrep -e EXP_VERSION\= $script | cut -f2 -d=`" \n Correct version is ${EXP_CURRENT_VERSION} \n Module $script skipped.\n"
		logger -p daemon.notice -t explorer "${TEXT}"
		echo "${TEXT}" >> ${EXP_TARGET}/${script##*/}.error
		logfile "${TEXT}"
	fi
    done
else
    for script in ${EXP_HOME}/tools/*
    do
	if [ "${EXP_CURRENT_VERSION}" = "`egrep -e EXP_VERSION\= $script | cut -f2 -d=`" ]
	then
		ksh -p $script $*
	else
		[ ! -d "{EXP_TARGET}/${script##*/}" ] && { mkdir -p ${EXP_TARGET}/${script##*/}; }
		TEXT="\n Explorer module $script version is "`egrep -e EXP_VERSION\= $script | cut -f2 -d=`" \n Correct version is ${EXP_CURRENT_VERSION} \n Module $script skipped.\n"
		logger -p daemon.notice -t explorer "${TEXT}"
		echo "${TEXT}" >> ${EXP_TARGET}/${script##*/}.error
		logfile "${TEXT}"
		echo "Explorer Module $script skipped \n"
	fi
    done
fi
# logfile NOTNOISE "data collection complete"
TEXT=`gettext "data collection complete"`
logfile NOTNOISE "${TEXT}"

#
#  POST PROCESSING
#

# Remove any zero length files from explorer output
find ${EXP_TARGET} -name '*.err' -size 0 -mount -exec rm {} \; 1>/dev/null 2>&1

# Post processing (IP address masking)
ksh -p ${EXP_LIB}/exp_postproc $*

# Set finish time
EXP_STOP=`date -u '+%Y.%m.%d.%H.%M'`

# Generate parse data
gen_parse_data

#
#  TRANSPORT
#

# Use system gzip before explorer gzip (check in C locale)
LC_SAVE=${LC_ALL}
export LC_ALL=C
EXP_GZIP=`type gzip 2>&1 | sed 's/.* \//\//g'`
export LC_ALL=${LC_SAVE}

if echo "${EXP_GZIP}" | egrep -s -e "not found"
then
    EXP_GZIP="${EXP_HOME}/bin/gzip.`uname -p`"
fi

logfile "EXP_GZIP=${EXP_GZIP}"
EXP_FNAME=`basename ${EXP_TARGET}`
EXP_FILE="${EXP_FNAME}.tar.gz"

REL=`uname -r | nawk -F. '{ print $2 }'`
case ${REL} in
    3|4|5|6)
	# Pathname fix for tar (5.6 or lower)
	cd ${EXP_TARGET}/..
	MAX=`find ${EXP_FNAME} -type f -print | nawk '{ print length, $0 }' | sort -rn | head -1`
	DIRLEN=`dirname ${MAX} | nawk '{ print length }'`
	PATHLEN=`basename ${MAX} | nawk '{ print length }'`

	#
	# length of directory must be less than 155 and the
	# length of filename must be less than 100 characters
	# for tar to work correctly
	#
	if [ "${DIRLEN}" -ge 155 -o "${PATHLEN}" -ge 100 ]
	then
	    cd ${EXP_TARGET}

	    # Get list of directories to tar, create exclude file
	    DIRS=""
	    for dir in *
	    do
		[ ! -d "$dir" ] && continue
		DIRS="${DIRS} $dir"
		echo "${EXP_FNAME}/$dir" >> ${EXP_TMPDIR}/exclude.${EXP_PID}
	    done

	    if [ -n "${DIRS}" ]
	    then
		# Create tar of DIRS
		LC_SAVE=${LC_ALL}
		export LC_ALL=C
		tar cf data.tar ${DIRS}
		export LC_ALL=${LC_SAVE}
	    fi

	    # Tar and compress with gzip
	    cd ${EXP_TMPDIR}
	    LC_SAVE=${LC_ALL}
	    export LC_ALL=C
	    tar cfX - ${EXP_TMPDIR}/exclude.${EXP_PID} ${EXP_FNAME} | ${EXP_GZIP} -c >${EXP_FILE}
	    export LC_ALL=${LC_SAVE}
	    # logfile "${EXP_FILE} created"
	    TEXT=`gettext "%s created"`
	    TEXT=`printf "${TEXT}" "${EXP_FILE}"`
	    logfile "${TEXT}"

	    # Remove data.tar from unpacked output
	    rm -f ${EXP_TARGET}/data.tar
	else
	    # Tar and compress with gzip
	    cd ${EXP_TMPDIR}
	    LC_SAVE=${LC_ALL}
	    export LC_ALL=C
	    tar cf - ${EXP_FNAME} | ${EXP_GZIP} -c >${EXP_FILE}
	    export LC_ALL=${LC_SAVE}
	    # logfile "${EXP_FILE} created"
	    TEXT=`gettext "%s created"`
	    TEXT=`printf "${TEXT}" "${EXP_FILE}"`
	    logfile "${TEXT}"
	fi
	;;
    *)
	# Tar and compress with gzip
	cd ${EXP_TMPDIR}
	LC_SAVE=${LC_ALL}
	export LC_ALL=C
	tar Ecf - ${EXP_FNAME} | ${EXP_GZIP} -c >${EXP_FILE}
	export LC_ALL=${LC_SAVE}
	# logfile "${EXP_FILE} created"
	TEXT=`gettext "%s created"`
	TEXT=`printf "${TEXT}" "${EXP_FILE}"`
	logfile "${TEXT}"
	;;
esac

# Send the tarball
if [ -n "${EXP_TRANSPORT}" ]
then
    # Make sure EXP_REPLY is available to the transports
    ksh -p ${EXP_LIB}/exp_transport $*
fi

# Clean up
if [ -n "${EXP_STDERR}" ] && [ -s "${EXP_STDERR}" ] 
then
    # logfile STDERROR "= = = stderr output from explorer = = ="
    TEXT=`gettext "= = = stderr output from explorer = = ="`
    logfile STDERROR "${TEXT}"
    while read line
    do
	logfile STDERROR "$line"
    done < "${EXP_STDERR}"
fi
test -n "${EXP_STDERR}" && rm -f ${EXP_STDERR}

# Remove old explorer runs if needed
DIR=`dirname ${EXP_TARGET}`
if [ -z "${EXP_KEEP}" ]
then
    # logfile NOTNOISE "removing previous explorers from ${DIR}"
    TEXT=`gettext "removing previous explorers from %s"`
    TEXT=`printf "${TEXT}" "${DIR}"`
    logfile NOTNOISE "${TEXT}"
    cd "${DIR}"

    for i in explorer.`hostid`.`uname -n`-*
    do
	# Keep the most current (directory and tarball)
	test "$i" = "${EXP_ID}"   && continue
	test "$i" = "${EXP_FILE}" && continue

	# Remove old directories
	rm -rf $i
    done
fi

# Remove uncompressed directory if told to.
if [ ! -z "${EXP_DELETE}" ]
then
   TEXT=`gettext "removing the uncompressed directory from %s"`
   TEXT=`printf "${TEXT}" "${DIR}"`
   logfile NOTNOISE "${TEXT}"
   cd "${DIR}"

   rm -rf "${EXP_ID}"
fi

# Log to /var/adm/messages
TEXT=`gettext "Explorer finished"`
logger -p daemon.notice -t explorer "${TEXT}"
logfile NOTNOISE "${TEXT}"
clean 1

exit 0
fi
