#!/bin/sh
#set -x

# get current path which includes gatherlogs.sh 
path=$(cd `dirname $0`;pwd)

datetime=`date +"%m-%d-%Y_%H-%M-%S"`
tarName=`echo "$path/HPSUM_Logs_${datetime}.tar"`
tmpFile=`echo "directory_listing.txt"`
hpsumDirListing="hpsum_directory_listing.txt"
syslogFile="syslog.log"
oldsyslogFile="OLDsyslog.log"

#determine which zip program to use, or none
gzip=`which gzip 2>/dev/null`
compress=`which compress 2>/dev/null`

if [ "x$gzip" != "x" ]; then
	zipper=$gzip
else
	if [ "x$compress" != "x" ]; then
		zipper=$compress
	else
		#no zip
		zipper="touch"
	fi
fi

echo "Gathering HPSUM logs..."
found=0

#listing of current dir and sub dir, usually dir running HPSUM, to capture files, dates/times
ls -Rl > $tmpFile


if [ ! -f $tmpFile ];then 
    tarName="/tmp/HPSUM_Logs_${datetime}.tar"
    tmpFile="/tmp/.directory_listing.txt"
    hpsumDirListing="/tmp/hpsum_directory_listing.txt"
    syslogFile="/tmp/syslog.log"
    oldsyslogFile="/tmp/OLDsyslog.log"
    ls -Rl > $tmpFile
fi

tar -cf $tarName $tmpFile
rm $tmpFile

# firmware wrapper logs
if [ -d /var/log/hp-sum ]; then
  tar -rf $tarName /var/log/hp-sum/* 2>/dev/null
  found=1
fi

#HPSUM directory listing 
ls -Rl /tmp/HPSUM > $hpsumDirListing
tar -rf $tarName $hpsumDirListing
rm $hpsumDirListing

#debug logs
if [ -d /tmp/HPSUM ]; then
  find /tmp/HPSUM -name "*.txt" -o -name "*.log" -o -name "*.xml" -o -name "*.trace" -o -name "*.pdb*" -o -name "*.ini" |
  while read file; do
    tar -rf $tarName $file 2>/dev/null
  done
  found=1
fi

#user logs
if [ -d /var/hp/log ]; then
  tar -rf $tarName /var/hp/log/* 2>/dev/null
  found=1
fi

#component logs
if [ -d /var/cpq ]; then
  tar -rf $tarName /var/cpq/* 2>/dev/null
  found=1
fi

#system logs
if [ -f /var/adm/syslog/syslog.log ]; then
   tail -1000 /var/adm/syslog/syslog.log > $syslogFile 2>/dev/null
else
  if [ -f /var/log/messages ]; then 
     tail -1000 /var/log/messages > $syslogFile 2>/dev/null
  fi
fi
if [ -f $syslogFile ]; then
	tar -rf $tarName $syslogFile
	rm $syslogFile
fi

if [ -f /var/adm/syslog/OLDsyslog.log ]; then
   tail -1000 /var/adm/syslog/OLDsyslog.log > $oldsyslogFile 2>/dev/null
fi
if [ -f $oldsyslogFile ]; then
	tar -rf $tarName $oldsyslogFile
	rm $oldsyslogFile
fi

#zip if possible
if [ $found -eq 1 ]; then
  $zipper $tarName
  newName=`ls -1 $tarName*`
  echo "HPSUM logs are in $newName"
  exit 0
fi

rm $tarName
echo "No HPSUM logs found"
exit -1
