#!/bin/bash
#set -x

# get current path which includes gatherlogs.sh 
#path=$(cd "dirname $0";pwd)
path=$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )
arch=$(`echo uname -m` | tr '[a-z]' '[A-Z]')

tablestodrop="CNodeData:sshkeyfile_location_h_STRING,sshkeyfile_passphrase_h_STRING,username_h_STRING,password_h_STRING,su_username_h_STRING,su_password_h_STRING,ass_username_h_STRING,ass_password_h_STRING,vcenter_username_h_STRING,vcenter_password_h_STRING,ilo_username_h_STRING,ilo_password_h_STRING \
CSessionSettings:proxy_username_h_STRING,proxy_password_h_STRING,icm_token_id_h_STRING \
CMoonshotNodeData:switch_password_h_STRING,switch_enable_h_STRING,switchb_password_h_STRING,switchb_enable_h_STRING \
CBaseLineLocationTable:remote_only_credential_h_STRING \
CSessionData:passphrase_h_STRING"

#CScalableUpdateGroup:username_h_STRING,password_h_STRING \

suttablestodrop="CVcenterServerData:vcenter_password_h_STRING,vcenter_username_h_STRING \
CPartnerDataTable:password_h_STRING,username_h_STRING \
COneViewApplianceData:oneview_appliance_username_h_STRING,oneview_appliance_password_h_STRING"

if [[ "$arch" = "X86_64" ]]; then
    arch="x64"
elif [[ "$arch" = "IA64" ]]; then
    arch="ia64"
else
    arch="x86"
fi

droptable="${path}/${arch}/sum_drop_table_${arch}"

if [ ! -w "$path" ]; then
path=/var/tmp
fi
datetime=`date +"%m-%d-%Y_%H-%M-%S"`
tarName=`echo "$path/SUM_SUT_Logs_${datetime}.tar"`
tmpFile=`echo "directory_listing.txt"`
sumDirListing="sum_directory_listing.txt"
syslogFile="syslog.log"
oldsyslogFile="OLDsyslog.log"
topOutput="topOutput.txt"
fsState="fsState.txt"
upTime="upTime.txt"
debug_dir="/var/tmp/sut/sum"

#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 SUM logs..."
found=0

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


if [ ! -f $tmpFile ];then 
    tarName="$path/SUM_SUT_Logs_${datetime}.tar"
    tmpFile="$path/.directory_listing.txt"
    sumDirListing="$path/sum_directory_listing.txt"
    syslogFile="$path/syslog.log"
    oldsyslogFile="$path/OLDsyslog.log"
    topOutput="$path/topOutput.txt"
    fsState="$path/fsState.txt"
    upTime="$path/upTime.txt"
    ls -Rl > $tmpFile
fi

tar -cf "$tarName" "$tmpFile"
rm "$tmpFile"

export LOGDIR=0
export SUTLOGS=0
function ParseCmdLine()
{
    ARGS=("$@")
    # get total subscripts in an array
    total=${#ARGS[*]}
   for (( i=0; i<=$(( $total -1 )); i++ ))
    do
        if [ "${ARGS[$i]}" == "--debuglogdir" -o "${ARGS[$i]}" == "-debuglogdir" ]; then
		i=`expr $i + 1`
	        debug_dir=${ARGS[$i]}  
	   elif [ "${ARGS[$i]}" == "--logdir" -o "${ARGS[$i]}" == "-logdir" ]; then  
		i=`expr $i + 1`
	        log_dir=${ARGS[$i]}	   
	   LOGDIR=1
	   elif [ "${ARGS[$i]}" == "-sutlogs" ]; then   
	   SUTLOGS=1
	   fi
	done
}

# This function searches for DB files from the directory passed in the argument,
# drops the tables and/or resets the columns from the tables for the DB file 
# and gathers the modifed DB file
function GatherDBFiles()
{
	directory="$1"
	isSUM="$2"

	# Find .pdb files and drop the tables and/or reset columns only in normal mode
	if [ "${PHOENIX}" = "1" ]; then
		return;
	fi

	# Fix for QXCR1001515420. Remove if any mod_*.pdb files exist.
	findCommand=`find "$directory" -name "mod_*.pdb"`
	for dbfilename in $findCommand
	do
		if [ "x${dbfilename}" != "x" ]; then
			rm -f "${dbfilename}" 2>/dev/null
		fi
	done
	if [ -f "${droptable}" ]; then
		if [ ${isSUM} = "true" ]; then
			findCommand=`find "$directory" -name "*.pdb"`
		else
			findCommand=`find "$directory" -name "*sut*.pdb"`
		fi
		for dbfilename in "$findCommand"
		do
			if [ "x${dbfilename}" = "x" ]; then
				continue;
			fi
			#Copy the db file and drop the tables from the new db file
			dir_name=$(dirname "$dbfilename");
			file_name=$(basename "$dbfilename");
			modifiedfile="$dir_name/mod_$file_name"
			cp -p "$dbfilename" "$modifiedfile"

			# Drop the tables using drop_table and gather it
			if [ ${isSUM} = "true" ]; then
				result=`"${droptable}" "$modifiedfile" ${tablestodrop} 2>&1`
			else
				result=`"${droptable}" "$modifiedfile" ${suttablestodrop} 2>&1`
			fi
			# If drop_table utility fails for any reason, don't gather the DB file
			if [[ $? != 0 ]]; then
				echo -e "${result}. Skipping ${dbfilename} file.\n"
				rm -f "$modifiedfile" 2>/dev/null
				continue
			fi
			tar -rf "$tarName" "$modifiedfile" 2>/dev/null
			rm -f "$modifiedfile"
		done
	else
		echo "\"${droptable}\" is not present. Skipping DB files."
	fi
}

ParseCmdLine "$@"
if [ $SUTLOGS -eq 0 ]; then
  #Gather system statistics
  if [ ${arch} = "ia64" ]; then
    top -f ${topOutput}
    bdf > ${fsState}
  else
    top -n 1 -b > ${topOutput}
    df > ${fsState}
  fi
  tar -rf "$tarName" "$topOutput"
  tar -rf "$tarName" "$fsState"
  uptime > ${upTime}
  tar -rf "$tarName" "$upTime"
  rm -f ${upTime} ${fsState} ${topOutput}
fi

tmpSUM=""
if [ -f hpsum.ini ];then 
	tmpSUM=`grep -E "^temp_dir" hpsum.ini | awk -F= '{print $2"/HPSUM"}'`
fi
if [ "x$tmpSUM" = "x" ]; then
	tmpSUM=/tmp/HPSUM
	if [ -f $tmpSUM/hpsum.ini ];then 
		tmp=`grep -E "^temp_dir" $tmpSUM/hpsum.ini | awk -F= '{print $2"/HPSUM"}'`
		if [ "x${tmp}" != "x" ]; then
			tmpSUM="${tmp}"
		fi
	fi
fi

varsum=""
if [ -f sum.ini ];then 
	varsum=`grep -E "^temp_dir" sum.ini | awk -F= '{print $2"/sum"}'`
fi
if [ "x$varsum" = "x" ]; then
	varsum=/var/tmp/sum	
	if [ -f $varsum/sum.ini ];then 
		tmp=`grep -E "^temp_dir" $varsum/sum.ini | awk -F= '{print $2"/sum"}'`
		if [ "x${tmp}" != "x" ]; then
			varsum="${tmp}"
		fi
	fi
fi

if [ $SUTLOGS -eq 0 ]; then
  #SUM directory listing
  if [ -d $tmpSUM ]; then 
	ls -Rl "$tmpSUM" > "$sumDirListing"
	echo "   " >> $sumDirListing
	echo Available disk space: >> "$sumDirListing"
	df -k >> "$sumDirListing"
	tar -rf "$tarName" "$sumDirListing"
	rm "$sumDirListing"
  fi
fi

#debug logs
if [ -d $tmpSUM ]; then
  if [ $SUTLOGS -eq 0 ]; then
    findCommand=`find $tmpSUM -name "*.txt" -o -name "*.log" -o -name "*.xml" -o -name "*.trace" -o -name "*.ini"`
  else
    findCommand=`find $tmpSUM -name "node.log" -o -name "deploy.log" -o -name "Baseline.log" -o -name "inventory.log" -o -name "*sum_detail_log.txt" -o -name "*sum_log.txt" -o -name "engine.log" -o -name "root.log" -o -name "*_disc.xml"`
  fi
  echo $findCommand | while read file; do
    tar -rf "$tarName" $file 2>/dev/null
  done

  if [ $SUTLOGS -eq 0 ]; then
    GatherDBFiles ${tmpSUM} true
  fi

  found=1
fi

#new default debug logs
if [ -d "$varsum" ]; then
  if [ $SUTLOGS -eq 0 ]; then
    findCommand=`find "$varsum" -name "*.txt" -o -name "*.log" -o -name "*.xml" -o -name "*.trace" -o -name "*.ini" -o -name "*.json"`
  else
    findCommand=`find $varsum -name "node.log" -o -name "deploy.log" -o -name "Baseline.log" -o -name "inventory.log" -o -name "*sum_detail_log.txt" -o -name "*sum_log.txt" -o -name "engine.log" -o -name "root.log" -o -name "*_disc.xml"`
  fi

  echo $findCommand | while read file; do
    tar -rf "$tarName" $file 2>/dev/null
  done

  if [ $SUTLOGS -eq 0 ]; then
    GatherDBFiles "${varsum}" true
  fi

  found=1
fi

if [ -d "$debug_dir" ]; then
  if [ $SUTLOGS -eq 0 ]; then
    findCommand=`find "$debug_dir" -name "*.txt" -o -name "*.log" -o -name "*.xml" -o -name "*.trace" -o -name "*.ini" -o -name "*.json"`
  else
    findCommand=`find "$debug_dir" -name "node.log" -o -name "deploy.log" -o -name "Baseline.log" -o -name "inventory.log" -o -name "*sum_detail_log.txt" -o -name "*sum_log.txt" -o -name "engine.log" -o -name "root.log" -o -name "*_disc.xml"`
  fi

  echo "$findCommand" | while read file; do
   tar -rf "$tarName" "$file" 2>/dev/null
  done

  if [ $SUTLOGS -eq 0 ]; then
    GatherDBFiles "${debug_dir}" true
  fi

  found=1
fi

if [ $SUTLOGS -eq 0 ]; then
  ## User option user log directory
  if [ $LOGDIR -eq 1 ]; then
  if [ -d "$log_dir" ]; then
    tar -rf "$tarName" "$log_dir"/* 2>/dev/null
    found=1
  fi
  fi

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

  #user logs old directory.
  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

  #hpsutesxi logs
  if [ -d /opt/hp/hpsutesxi/bin ]; then
    findLogsCommand=`find /opt/hp/hpsutesxi -name "*.log" -o -name "HPSUM_Combined_Report_*.xml"`
    echo $findLogsCommand | while read file; do
      tar -rf "$tarName" $file 2>/dev/null
    done
    hpsutesxidb='/opt/hp/hpsutesxi'
    GatherDBFiles "${hpsutesxidb}" false
    found=1
  fi
  #sutesxi logs for versions >= 2.0
  if [ -d /opt/sutesxi/bin ] && [ -d /var/tmp/sutesxi ]; then
    findLogsCommand=`find /var/tmp/sutesxi -name "*.log" -o -name "sutesxi_service*.zip" -o -name "SUM_Combined_Report_*.xml" -o -name "inputfiledebug.txt"`
    echo $findLogsCommand | while read file; do
      tar -rf "$tarName" $file 2>/dev/null
    done
    hpsutesxidb='/var/tmp/sutesxi/'
    GatherDBFiles "${hpsutesxidb}" false
    found=1
  fi

else
  #flash.debug logs
  if [ -d /var/cpq ]; then
    tar -rf "$tarName" /var/cpq/flash.debug.log 2>/dev/null
    found=1
  fi
fi

echo "Gathering SUT logs..."
#hpsut logs
if [ -d /opt/hp/hpsut/bin ]; then
  findLogsCommand=`find /opt/hp/hpsut -name "*sut*.log" -o -name "*SUM_Combined_Report_*.xml" -o -name "*inputfile.txt"`
  echo $findLogsCommand | while read file; do
    tar -rf "$tarName" $file 2>/dev/null
  done
  found=1
fi

#sut logs for versions >= 2.0
if [ -d /opt/sut/bin ] && [ -d /var/tmp/sut ]; then
   findLogsCommand=`find /var/tmp/sut -name "*sut*.log" -o -name "*SUM_Combined_Report*.xml" -o -name "*inputfile.txt" -o -name "ilorest.log" -o -name "*libhpsrv*.log"`
  echo $findLogsCommand | while read file; do
    tar -rf "$tarName" $file 2>/dev/null
    tar -rf "$tarName" /var/log/sut/* 2>/dev/null
  done
  found=1
fi

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

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