#!/bin/bash
# $Copyright$
# Copyright (C) Fujitsu Siemens Computers GmbH 2009
# All rights reserved
#
# $Copyright$
# Copyright (c) Fujitsu Technology Solutions 2009, 2010, 2011, 2012, 2013
# All rights reserved
#
SVER=1.16
SDATE="2012 05 15"
TOTALSTEPS=56
STEP=0;

#catch Term signals
	trap Cleanup 1 2 3 6 9 15
	
# Environment:
		zipFileExt="zip"
		tmp=$(type zip 2>&1) || zipFileExt="tar.gz"
		
	# SV communication file path
		SVFILE=/var/tmp/PrimeCollect.txt

	# SV data file path
		SVDATAFILE=/etc/srvmagt/PrimeCollect_Data.$zipFileExt
	
	# Temporary file paths
		DataPath=/var/log/PrimeCollect
		TmpDataPath=$DataPath/tmp
		TmpPath=/tmp
		StandAlonePath=/tmp/PrimeCollect
		LockPath=$DataPath/lock
		SOSINPUT=$TmpDataPath/SosIn.txt
		AgentsPath=/etc/srvmagt

	# Logfile
		PCLog=$TmpDataPath/PrimeCollect.log
		PCTmpSpace=$TmpDataPath/PrimeCollectTempSpace.log

	# SVRaidPath
		SVRaidPath1=/opt/fujitsu/ServerViewSuite/RAIDManager
		SVRaidPath2=/opt/fsc/RAID
		if [ -d $SVRaidPath1 ]; then
			SVRaidPath=$SVRaidPath1
		else
			SVRaidPath=$SVRaidPath2
		fi

	# FlexFrame
		FlexFrameSAP=/opt/FlexFrame/bin
		FlexFrameOracle=/opt/SMAW/SMAWff4o/bin


##############################################################################
# Function Definitions
# Initialization / Cleanup
##############################################################################

ChkContext () {
	which id > /dev/null 2>&1
	if [ $? -eq 0 ]; then
		# Make sure only root can run our script
		if [ "$(id -u)" != "0" ]; then
			echo " "
			echo " "
			echo "++++++++++++++++++++++++++++++++++++++++++++++++++++++"
			echo "+ PrimeCollect must be executed as root ... abort    +"
			echo "++++++++++++++++++++++++++++++++++++++++++++++++++++++"
			echo " "
			
			exit 3
		fi
	fi
}


# check for another instance of PrimeCollect running
ChkOtherInst() {
	if [ -d $LockPath ]; then
		# Lock path already existing -- terminate
			echo " "
			echo "++++++++++++++++++++++++++++++++++++++++++++++++++++++"
			echo "+ Directory $LockPath exists.       +"
			echo "+ Please check, if another instance of PrimeCollect  +"
			echo "+ is already running. If yes, try again later.       +"
			echo "+ If not, remove the directory.                      +"
			echo "++++++++++++++++++++++++++++++++++++++++++++++++++++++"
			echo " "
			
			exit 2
	else
		# Check if data path exists -- create it
		CreateDataPath
		cd $DataPath
		if [ "$PWD" == "$DataPath" ]; then
			mkdir $LockPath
		fi
		
	fi	
}

# Release Lock directory
Unlock() {
	if [ -d $LockPath ]; then
		rmdir $LockPath > /dev/null 2>&1
	fi
}

# Initialize Provider File
InitSVFile() {
	PROGRESS=0
	RAID=1
	UTCSTAMP=0
	ERRMSG=

	# file handling not necessary in Standalone mode
	if [ $STANDALONE -eq 0 ]; then
		#write initial values
		UpdateSVFile
	fi
}

# Update Provider File
UpdateSVFile() {

	# file handling not necessary in Standalone mode
	if [ $STANDALONE -eq 0 ]; then
		echo -e "[Status]\nProgress =$PROGRESS\nRaid =$RAID\nCreateTime =$UTCSTAMP\nErrMsg =$ERRMSG\n" > $SVFILE
	fi
}

# Check for Temp Directory and delete content
CleanTmpDir() {
	if [ -d $DataPath ]; then
		# Data path existing 
		cd $DataPath
		if [ "$PWD" == "$DataPath" ]; then
			# Now we are in $DataPath
			# Check for an existing TmpDataPath
			if [ -d $TmpDataPath ]; then
				# Temp data path existing 
				# Delete all files in temp directory
				rm -rf -v $TmpDataPath >> TempPrint 2>&1
				dprint `more TempPrint`
				rm -f TempPrint
			fi
		fi
	fi	
			
	# remove $TmpDataPath directory itself
	cd $DataPath
	if [ -d $TmpDataPath ]; then
		rmdir $TmpDataPath > /dev/null 2>&1
	fi

	dprint "Cleanup directory: $TmpDataPath --- DONE"
}


# Check for Standalone Mode Directory and delete content
CleanStandAloneDir() {
	if [ -d $TmpPath ]; then
		# Tmp path existing 
		cd $TmpPath
		if [ "$PWD" == "$TmpPath" ]; then
			# Now we are in TmpPath
			# Check for an existing StandAlonePath
			if [ -d $StandAlonePath ]; then
				# StandAlonePath existing 
				# Delete all files in StandAlonePath directory
				rm -rf -v $StandAlonePath >> TempPrint 2>&1
				dprint `more TempPrint`
				rm -f TempPrint
			fi
		fi
	fi	
			
	# remove $StandAlonePath directory itself
	cd $TmpPath
	if [ -d $StandAlonePath ]; then
		rmdir $StandAlonePath > /dev/null 2>&1
	fi

	dprint "Cleanup directory: $StandAlonePath --- DONE"
}


# Create data path and temporary data path
CreateDataPath() {
	if [ -d $DataPath ]; then
		dprint "Data directory existing: $DataPath"
	else
		dprint "Create data Directory: $DataPath"
		mkdir $DataPath
	fi


	if [ -d $TmpDataPath ]; then
		dprint "Temp Directory existing: $TmpDataPath"
	else
		dprint "Create Temp Directory: $TmpDataPath"
		mkdir $TmpDataPath
	fi
}

TurnOnCron()
{
	[ $CronTurnedOff -eq 1  ] &&
		# Turn on periodical supervision of srvmagt daemons
		echo "" > /etc/srvmagt/srvmagtCronOn
}

Cleanup()
{
	echo " "
	echo " "
	echo "++++++++++++++++++++++++++++++++++++++++++++++++++++++"
	echo "+ Caught Signal ... cleaning up                      +"
	echo "++++++++++++++++++++++++++++++++++++++++++++++++++++++"
	echo " "
	
	CleanTmpDir
	
	# Initialize Provider File
	InitSVFile
	
	# Release Lock directory
	Unlock
	
	TurnOnCron

	echo " "
	echo "++++++++++++++++++++++++++++++++++++++++++++++++++++++"
	echo "+ Done cleanup  ... quitting                         +"
	echo "++++++++++++++++++++++++++++++++++++++++++++++++++++++"
	exit 1
}


##############################################################################
# Function Definitions
# Logging
##############################################################################
title() {
	printboth " "
	printboth " "
	printboth " "
	printboth "******************************************************"
	printboth "******************************************************"
	printboth "******************************************************"
	printboth "***  Fujitsu Technology Solutions - PrimeCollect   ***"
	printboth "***            Script Version: $SVER                ***"
	printboth "***            Script Date: $SDATE             ***"
	printboth "******************************************************"
	printboth "******************************************************"
	printboth "******************************************************"
	printboth " "
	printboth "Current Timestamp:      `LC_ALL=C date "+%F-%T"`"
	printboth "Data directory:         $DataPath"
}

# Print / Log function
# Write used temp space to logfile
printspace() {
    printf "%s\nTempSpace[KB]:`du -s -b --block-size=1024 $TmpDataPath`\n\n" "$@" >> $PCTmpSpace
}

# Print / Log function
# Write Input params to console and to logfile
printboth() {
	printf "%s\n" "$@" | tee -a $PCLog
}

# Print / Log function
# Write headline to console and to logfile
printHeaderBoth() {
    printf "\n++++++++++++++++++++++++++++++++++++++++++++++++++++++\n" "$@" | tee -a $PCLog
    printf "+ %s\n" "$@" | tee -a $PCLog
    printf "++++++++++++++++++++++++++++++++++++++++++++++++++++++\n" "$@" | tee -a $PCLog
}

# Print / Log function
# Write Input params to console and to logfile
# Increase progress counter depending on $2
# Print Error message depending on $RETVAL
printbothlog() {
	if [ "$2" != "NoProgress" ]; then
		let STEP=$STEP+1
		let PROGRESS=(100*STEP)/TOTALSTEPS
		if [ $PROGRESS -ge 100 ]; then
			echo `LC_ALL=C date "+%F-%T"`: Progress= 99%;
			UpdateSVFile
		else
			echo `LC_ALL=C date "+%F-%T"`: Progress= $PROGRESS%;
			UpdateSVFile
		fi
	fi

	if [ $RETVAL -eq 0 ]; then
		RETVAL=DONE
	else
	    RETVAL=FAIL
		if [ -f tmp.err ]; then
			cat tmp.err | tee -a $PCLog
			rm tmp.err
		fi
	    
	fi
	printf "%-48s: $RETVAL\n" "$1" | tee -a $PCLog
}




# Verbose mode only
# Print / Log function
# Write Input params to console
dprint() {
	if [ $VERBOSE -eq 1 ]; then
		printf "%s\n" "$@"
	fi
}

# Verbose mode only
# Print / Log function
# Write Input params to console and to logfile
dprintboth() {
	if [ $VERBOSE -eq 1 ]; then
		printf "%s\n" "$@" | tee -a $PCLog
	fi
}

# Verbose mode
# List the Temp Directory
ShowTempDir() {
	if [ $VERBOSE -eq 1 ]; then
		cd $TmpDataPath
		echo "Content of  Temp Directory:"
		pwd
		ls -R -la;
	fi
}

# Verbose mode
# Show Logfile on Console
ShowLog() {
	if [ $VERBOSE -eq 1 ]; then
		more $PCLog;
	fi
}

##############################################################################
# Function Definitions
# Data Collection
##############################################################################
# set Agents function path
SetFunctionPath() {
	if [ $STANDALONE -eq 0 ]; then
		if [ -f /etc/srvmagt/functions ]; then
			FuncPath=$AgentsPath
			FuncPathFound=1
			printboth "Function library path (Agent mode):"
			printboth "   $FuncPath/functions"
		else
			printboth "Error: Function library (Agent mode) not found"
		fi
	else
		if [ -f /tmp/PrimeCollect/functions ]; then
			FuncPath=$StandAlonePath
			FuncPathFound=1
			printboth "Function library path (Standalone mode):"
			printboth "   $FuncPath/functions"
		else
			printboth "Error: Function library (Standalone mode) not found"
		fi
	fi
}


# ServerView Agents Check
# Checks if we are running in a ServerView / Standalone context
# Log result to console and to lofile
CheckSVAgents() {
	CronTurnedOff=0
	if [ $STANDALONE -eq 0 ]; then
		if [ -f /etc/srvmagt/functions ]; then
			. /etc/srvmagt/functions
			AgentsInstalled=1
			printboth "Running in SV context (Agent Mode)"
			# Turn off periodical supervision of srvmagt daemons
			[ -f /etc/srvmagt/srvmagtCronOn ] && CronTurnedOff=1 &&
				rm -f /etc/srvmagt/srvmagtCronOn
		else
			AgentsInstalled=0
			printboth "No SV context found (Agent Mode)"
		fi
	else
		printboth "Running in Standalone Mode"
	fi 
}

# Check Distribution
# SV Agents needed
# Searches for the installed distribution 
# Log result to console and to lofile
CheckDistrib() {
	if [ -f $FuncPath/functions ]; then
		. $FuncPath/functions

		SetSvEnv
		echo $SV_OS
		echo $SV_NICKNAME

		case $SV_NICKNAME in

		SLES9 | SLES10 | SLES11)
			Distributor=Suse
			printboth "Result: $SV_NICKNAME -- distributor supported"
			;;

		ESX*)
			Distributor=VMware
			printboth "Result: $SV_NICKNAME -- distributor supported"
			;;

		RHEL*)
			Distributor=Redhat
			printboth "Result: $SV_NICKNAME -- distributor supported"
			;;

		XS*)
			Distributor=Citrix
			printboth "Result: $SV_NICKNAME -- distributor $Distributor supported"
			;;

		OL* | OVM*)
			Distributor=Oracle
			printboth "Result: $SV_NICKNAME -- distributor $Distributor supported"
			;;

		TLX*)
			Distributor=Turbolinux
			printboth "Result: $SV_NICKNAME -- distributor $Distributor supported"
			;;
			
		*)
			printboth "Result: $SV_NICKNAME -- distributor !! NOT!! supported"
			;;
		esac

		printboth "Found Distributor: $Distributor"
	
	else
		printboth "$FuncPath/functions not found -- Don't know how to check Distribution"
	fi
}

# Virtual Machine
# SV Agents needed
# Checks if we are running on a Virtual Machine 
# Log result to console and to lofile
CheckVM() {
		. $FuncPath/functions
		SetSvEnv
		if [ $? -eq 0 ]; then
			printboth "Result: $SV_RUNNINGONVM"
		else
			printboth "$FuncPath/functions not found -- Don't know how to check VM"
		fi
}

# Collect support relevant data using distributor tools
RunDistribTools() {
	if [ "$Distributor" == "Suse" -o "$Distributor" == "Citrix" ]; then
		# SUSE:   supportconfig
		which supportconfig > /dev/null 2>&1
		if [ $? -eq 0 ]; then
			supportconfig 2>tmp.err | tee -a $TmpDataPath/Supportconfig.log
			RETVAL=$?; 	printbothlog "Run Supportconfig"
		
			grep "Log file tar *ball:"  $TmpDataPath/Supportconfig.log > $TmpDataPath/sline 2>tmp.err
			RETVAL=$?
			if [ $RETVAL -ne 0 ]; then
				printbothlog "Grep Supportconfig result file"
				echo `more $TmpDataPath/sline` >>  $PCLog
			fi
			
			Supfile=`cat $TmpDataPath/sline | sed s"/.*Log file tar *ball: *//"` 2>tmp.err
			RETVAL=$?
			if [ $RETVAL -ne 0 ]; then
				printboth "Trim Supportconfig result file"
				printboth $Supfile
			else
				mv $Supfile $TmpDataPath >>  $PCLog 2>&1
				rm $TmpDataPath/sline > /dev/null 2>&1
			fi
		else
			printboth "supportconfig                                   : SKIP"
			printboth " "
		fi
	fi

	RH_SYSREP=1
	if [ "$Distributor" == "Redhat" -o "$Distributor" == "Citrix" -o "$Distributor" == "Oracle" ]; then
		# RedHat: sosreport
		which sosreport > /dev/null 2>&1
		if [ $? -eq 0 ]; then
			# don't run sysreport
				RH_SYSREP=0
		
			# check sosreport version
				sosreport --help > $TmpDataPath/sosreport.hlp
				grep "Gather information locally but don't package or submit" $TmpDataPath/sosreport.hlp > /dev/null 2>&1
				if [ $? -eq 0 ]; then
					S_MODE=1
					printboth "run sosreport with -g -f -v -norpm option"
				else
					S_MODE=2
					grep "disable multi-threaded gathering mode" $TmpDataPath/sosreport.hlp > /dev/null 2>&1
					if [ $? -eq 0 ]; then
						printboth "run sosreport with -v --no-progressbar -k rpm.rpmva=off option"
					else
						printboth "run sosreport"
					fi
				fi

			echo " "
			echo "RedHat Diagnostic Tool sosreport started ...."
			echo " "
			echo "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"
			echo "!!! Please wait, this may last approximately 5 minutes .... !!!"
			echo "!!!       NO Screen-update will be done for this time       !!!"
			echo "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"
			echo " "

			if [ $S_MODE -eq 1 ]; then
				# start old version of sosreport

				sosreport -g -f -v -norpm | tee -a $TmpDataPath/sosreport.log 2>tmp.err
				RETVAL=$?; 	printbothlog "Run sosreport"

				grep "Collected information is in "  $TmpDataPath/sosreport.log > $TmpDataPath/sline 2>tmp.err
				RETVAL=$?
				if [ $RETVAL -ne 0 ]; then
					printbothlog "Grep Sosreport result file"
					echo `more $TmpDataPath/sline` >>  $PCLog
				fi
				
				Supfile=`cat $TmpDataPath/sline | sed s"/Collected information is in //"` 2>tmp.err
				RETVAL=$?
				if [ $RETVAL -ne 0 ]; then
					printboth "Trim Sosreport result file"
					printboth $Supfile
				else
					zipFile sosreport $Supfile

					Supfile=`cat $TmpDataPath/sline | sed s"/Collected information is in \/tmp\/sos_//"` 2>tmp.err
					RETVAL=$?
					if [ $RETVAL -ne 0 ]; then
						printboth "Trim Sosreport directory file"
						printboth $Supfile
					else
						# sosreport data are expected in /tmp/sos_$Supfile
						cd /tmp
						rm -rf -v /tmp/sos_$Supfile >> TempPrint 2>&1
						dprint `more TempPrint`
						rm -f TempPrint
					fi
					rm $TmpDataPath/sline > /dev/null 2>&1
				fi
			else
				# start new version of sosreport
				echo -e "\ny\ny\n" > $SOSINPUT
				if [ "$SV_NICKNAME" = "RHEL6" -o  "$Distributor" == "Oracle" ]; then
					sosreport -v -k rpm.rpmva=off < $SOSINPUT 2>tmp.err | tee -a $TmpDataPath/sosreport.log
				else
					sosreport -v --no-progressbar  -k rpm.rpmva=off < $SOSINPUT 2>tmp.err | tee -a $TmpDataPath/sosreport.log
				fi
				RETVAL=$?; 	printbothlog "Run Sosreport"

				grep "/tmp/sosreport"  $TmpDataPath/sosreport.log > $TmpDataPath/sline 2>tmp.err
				RETVAL=$?
				if [ $RETVAL -ne 0 ]; then
					printbothlog "Grep Sosreport result file"
					echo `more $TmpDataPath/sline` >>  $PCLog
				else
					mv `more $TmpDataPath/sline` $TmpDataPath >>  $PCLog 2>tmp.err
					RETVAL=$?; 	printbothlog "cp sosreport archive"
					
					mv `more $TmpDataPath/sline`.md5 $TmpDataPath >>  $PCLog 2>tmp.err
					RETVAL=$?; 	printbothlog "cp sosreport archive md5"
					rm $TmpDataPath/sline > /dev/null 2>&1
					rm $SOSINPUT > /dev/null 2>&1
				fi
			fi
		else
			printboth " "
			printboth "sosreport                                       : SKIP"
		fi
	fi
	
	if [ $RH_SYSREP -eq 1 ]; then
		if [ "$Distributor" == "Redhat" -o "$Distributor" == "Citrix" -o "$Distributor" == "Oracle" ]; then
			# RedHat: sysreport
			which sysreport > /dev/null 2>&1
			if [ $? -eq 0 ]; then
				echo " "
				echo "RedHat Diagnostic Tool sysreport started ...."
				echo "Please wait, this may last a few minutes ...."
				echo " "

				sysreport -norpm  < /dev/null 2>tmp.err | tee $TmpDataPath/sysreport.log
				RETVAL=$?; 	printbothlog "Run sysreport"

				grep " to your support"  $TmpDataPath/sysreport.log > $TmpDataPath/sline 2>tmp.err
				RETVAL=$?
				if [ $RETVAL -ne 0 ]; then
					printbothlog "Grep Sysreport result file"
					echo `more $TmpDataPath/sline` >>  $PCLog
				fi
				
				cat $TmpDataPath/sline | sed s"/ to your support//" 1>sline2  2>tmp.err
				Supfile=`cat $TmpDataPath/sline2 | sed s"/Please send //"` 2>tmp.err
				RETVAL=$?
				if [ $RETVAL -ne 0 ]; then
					printbothlog "Trim Sysreport result file"
					echo $Supfile
				else
					mv $Supfile $TmpDataPath >>  $PCLog 2>&1
					rm $TmpDataPath/sline  > /dev/null 2>&1
					rm $TmpDataPath/sline2 > /dev/null 2>&1
				fi
			else
				printboth " "
				printboth "sysreport                                       : SKIP"
			fi
		fi
	fi

	if [ "$Distributor" == "VMware" ]; then
		# VM ESX:   vm-support
		which vm-support > /dev/null 2>&1
		if [ $? -eq 0 ]; then

			echo " "
			echo "VMware ESX Server Support Script started ...."
			echo " "
			echo "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"
			echo "!!!    Please wait, this may last up to 5 minutes ....      !!!"
			echo "!!!              NO input is necessary                      !!!"
			echo "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"
			echo " "

			vm-support -w $TmpDataPath 2>tmp.err | tee -a $TmpDataPath/vm_support.log
			RETVAL=$?; 	
			if [ $RETVAL -eq 0 ]; then
				printboth "vm-support logfile written to: vm_support.log"
				printboth "vm-support result: esx-YYYY-mm-dd--HH.MM.xxx.tgz"
			fi
			printbothlog "VMware ESX Server Support Script"
		else
			printboth " "
			printboth "VMware ESX Server Support Script                : SKIP"
		fi
	fi
	
}

# Collect support relevant data using own tools (part 1)
RunTools_1() {
	cd $TmpDataPath
	
	# SV Archive file
		if [ -f $FuncPath/archive ]; then
			echo " "
			echo "ServerView archive creation started ...."
			echo " "
			echo "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"
			echo "!!! Please wait, this may last approximately 5 minutes .... !!!"
			echo "!!!       NO Screen-update will be done for this time       !!!"
			echo "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"
			echo " "

			$FuncPath/archive 2>&1  1>$TmpDataPath/SVArchive.log
			RETVAL=$?; 	printbothlog "ServerView archive creation"
			# Archive file will be copied later on during collecting directory
			# /var/log/srvmagt

		else
			printboth " "
			printboth "ServerView archive creation                     : SKIP"
		fi
}

# Collect support relevant data using own tools (part 2)
RunTools_2() {
	cd $TmpDataPath
	
	# PCSysScan is only available in Agent mode
	if [ $STANDALONE -eq 0 ]; then
		#PCSysScan
			if [ "$PWD" == "$TmpDataPath" ]; then
				printboth "PCSysScan started           ..."
				/usr/sbin/PCSysScan PCSysScan 2>tmp.err
				RETVAL=$?;
				if [ $RETVAL -eq 0 ]; then
					printboth "PCSysScan data written to: $TmpDataPath/PCSysScan.xml "
				fi
	 			printboth " "
	 			printbothlog "PCSysScan"
			fi
	fi

	# IRMCView
 		printboth " "
		if [ -f $FuncPath/irmcview ]; then
			$FuncPath/irmcview -A 1>$TmpDataPath/irmcview.log 2>tmp.err
			RETVAL=$?; 	printbothlog "Run irmcview with option -a"
		else
			printboth "irmcview (not found)                            : SKIP"
			printboth " "
		fi

	# dmidecode_own
		if [ -f $FuncPath/dmidecodeSV ]; then
			$FuncPath/dmidecodeSV   1>$TmpDataPath/dmidecodeSV.log 2>tmp.err 
			RETVAL=$?; 	printbothlog "dmidecodeSV"
		else
			printboth "dmidecodeSV (not found)                        : SKIP"
			printboth " "
		fi
		
	# MegaRAID 
		if [ -f $FuncPath/MRgetLog ]; then
			$FuncPath/MRgetLog   2>tmp.err 
			RETVAL=$?; 	printbothlog "MRgetLog"
		else
			printboth "MRgetLog (not found)	                          : SKIP"
			printboth " "
		fi
		
	# SVRAID (ServerView RAID)
		if [ -d $SVRaidPath ]; then
			# ServerView Raid Path exists 
			cd $SVRaidPath
			if [ "$PWD" == "$SVRaidPath" ]; then
			printboth "SVRaidPath=$SVRaidPath"
			
				# copy SVRaid Snapshot
					if [ -f bin/snapshot.xml ]; then
						cp bin/snapshot.xml $TmpDataPath >>  $PCLog 2>tmp.err
						RETVAL=$?; 	printbothlog "SVRAID (copy Snapshot.xml)"
					fi
				# copy SVRaid Logfile
					if [ -f web/public/RAIDLog.xml ]; then
						cp web/public/RAIDLog.xml $TmpDataPath >>  $PCLog 2>tmp.err
						RETVAL=$?; 	printbothlog "SVRAID (copy RAIDLog.xml)"
					fi
					if [ -f web/public/RAIDLog.xsl ]; then
						cp web/public/RAIDLog.xsl $TmpDataPath >>  $PCLog 2>tmp.err
						RETVAL=$?; 	printbothlog "SVRAID (copy RAIDLog.xsl)"
					fi
				# copy SVRaid System and RAID configuration
					which amCLI > /dev/null 2>&1
					if [ $? -eq 0 ]; then
						# SVRAID found -- set Provider file marker
							RAID=1
						# System information
							amCLI -l all 1>$TmpDataPath/SVRaid_System.txt 2>tmp.err 
							RETVAL=$?; 	printbothlog "SVRAID (get system information)"
						# RAID information
							amCLI -w 21/3 1>$TmpDataPath/SVRaid_Config.txt 2>tmp.err 
							RETVAL=$?; 	printbothlog "SVRAID (get RAID information)"
					else
						# SVRAID not found -- set Provider file marker
							RAID=0
						printboth " "
						printboth "SVRAID (amCLI not found)                       : SKIP"
					fi
			else
				# SVRAID not found -- set Provider file marker
					RAID=0
				printboth " "
				printboth "SVRAID (cannot locate)                          : SKIP"
			fi
		else
			# SVRAID not found -- set Provider file marker
				RAID=0
			printboth " "
			printboth "SVRAID (Path not found)                         : SKIP"
		fi
	
	# FlexFrame Status (SAP)
		if [ -d $FlexFrameSAP ]; then
			# FlexFrame path for SAP exists 
			cd $FlexFrameSAP
			if [ "$PWD" == "$FlexFrameSAP" ]; then
				which ff_startconfig.sh > /dev/null 2>&1
				if [ $? -eq 0 ]; then
					ff_startconfig.sh 1>$TmpDataPath/FlexFrame_startconfig.txt 2>tmp.err 
					RETVAL=$?; 	printbothlog "FlexFrame (SAP) config"
				else
					printboth " "
					printboth "FlexFrame (startconfig not found)               : SKIP"
				fi
			else
				printboth " "
				printboth "FlexFrame SAP (cannot locate)                   : SKIP"
			fi
		else
			printboth " "
			printboth "FlexFrame (SAP)                                 : SKIP"
		fi
	
	# FlexFrame Status (Oracle)
		if [ -d $FlexFrameOracle ]; then
			# FlexFrame path for Oracle exists 
			cd $FlexFrameOracle
			if [ "$PWD" == "$FlexFrameOracle" ]; then
				which ff4o_collect_diag.sh > /dev/null 2>&1
				if [ $? -eq 0 ]; then
					ff4o_collect_diag.sh 1>$TmpDataPath/FlexFrame_4o_collect_diag.txt 2>tmp.err 
					RETVAL=$?; 	printbothlog "FlexFrame (Oracle) diagnostics"
				else
					printboth " "
					printboth "FlexFrame (ff4o_collect_diagt not found)        : SKIP"
				fi
			else
				printboth " "
				printboth "FlexFrame Oracle (cannot locate)                : SKIP"
			fi
		else
			printboth " "
			printboth "FlexFrame (Oracle)                              : SKIP"
		fi
	
	# eecdcp is only available in Agent mode
	if [ $STANDALONE -eq 0 ]; then
		# Agent Mode
		if [ -f /etc/srvmagt/functions ]; then
			# Agents installed
			/etc/init.d/eecd status > /dev/null 2>&1
			if [ $? -eq 0 ]; then
				# eecd running
				eecdcp -t 1>$TmpDataPath/eecdcp.log 2>tmp.err
				printboth " "
				RETVAL=$?; 	printbothlog "Run eecdcp with option -t"
			fi
		fi
	fi 

}

# Collect MCO data (only on PRIMEQUEST)
CollectMCOdata() {
	 /opt/fujitsu/SVmco/sh/getosvmco $TmpDataPath/getosvmco-data  2>tmp.err
	RETVAL=$?; 	printbothlog "getosvmco"

}

# Collect support relevant data using standard tools
CollectStdTools() {
	dmidecode   1>$TmpDataPath/dmidecode.txt 2>tmp.err 
	RETVAL=$?; 	printbothlog "dmidecode"

	ifconfig -a 1>$TmpDataPath/ifconfig.txt 2>tmp.err
	RETVAL=$?; 	printbothlog "ifconfig -a"

	lspci       1>$TmpDataPath/lspci.out 2>tmp.err
	RETVAL=$?; 	printbothlog "lspci"

	df -h       1>$TmpDataPath/df.out 2>tmp.err
	RETVAL=$?; 	printbothlog "df -h"

	fdisk -l    1>$TmpDataPath/fdisk.out 2>tmp.err
	RETVAL=$?; 	printbothlog "fdisk -l"

	lsmod       1>$TmpDataPath/lsmod.out 2>tmp.err
	RETVAL=$?; 	printbothlog "lsmod"

	rpm -qa     1>$TmpDataPath/rpm.txt 2>tmp.err
	RETVAL=$?; 	printbothlog "rpm -qa"

	uname -a    1>$TmpDataPath/out_uname 2>tmp.err
	RETVAL=$?; 	printbothlog "uname -a"

}


# Collect support relevant files (1) 
Collectfiles_1() {

	zipFile var_log_messages /var/log/messages
	
	RETVAL=$?; 	printbothlog "cp /var/log/messages"

	cp /var/log/boot.log $TmpDataPath >>  $PCLog 2>tmp.err
	RETVAL=$?; 	printbothlog "cp /var/log/boot.log"

	cp /boot/message $TmpDataPath >>  $PCLog 2>tmp.err
	RETVAL=$?; 	printbothlog "cp /boot/message"

	cp /proc/cmdline $TmpDataPath >>  $PCLog 2>tmp.err
	RETVAL=$?; 	printbothlog "cp /proc/cmdline"

	cp /proc/scsi/scsi $TmpDataPath >>  $PCLog 2>tmp.err
	RETVAL=$?; 	printbothlog "cp /proc/scsi/scsi"

	cp /proc/interrupts $TmpDataPath >>  $PCLog 2>tmp.err
	RETVAL=$?; 	printbothlog "cp /proc/interrupts"

	cp /proc/cpuinfo $TmpDataPath >>  $PCLog 2>tmp.err
	RETVAL=$?; 	printbothlog "cp /proc/cpuinfo"

	cp /proc/meminfo $TmpDataPath >>  $PCLog 2>tmp.err
	RETVAL=$?; 	printbothlog "cp /proc/meminfo"

	cp /etc/srvmagt/Report.xslt $TmpDataPath >>  $PCLog 2>tmp.err
	RETVAL=$?; 	printbothlog "cp /etc/srvmagt/Report.xslt"

	# SV_NICKNAME has been set in CheckDistrib
		case $SV_NICKNAME in

		SLES9)
			cp /etc/snmpd.conf $TmpDataPath >>  $PCLog 2>tmp.err
			RETVAL=$?; 	printbothlog "cp /etc/snmpd.conf"
			;;
		*)
			cp /etc/snmp/snmpd.conf $TmpDataPath >>  $PCLog 2>tmp.err
			RETVAL=$?; 	printbothlog "cp /etc/snmp/snmpd.conf"
			;;
		esac

#SUSE
	if [ "$Distributor" == "Suse" -o "$Distributor" == "Citrix" ]; then
		cp /var/log/boot.msg $TmpDataPath >>  $PCLog 2>tmp.err
		RETVAL=$?; 	printbothlog "cp /var/log/boot.msg"

		cp /boot/grub/menu.lst $TmpDataPath >>  $PCLog 2>tmp.err
		RETVAL=$?; 	printbothlog "cp /boot/grub/menu.lst"

		cp /etc/SuSE-release $TmpDataPath >>  $PCLog 2>tmp.err
		RETVAL=$?; 	printbothlog "cp /etc/SuSE-release"
	fi
	

#REDHAT
	if [ "$Distributor" == "Redhat" -o "$Distributor" == "Citrix"  -o "$Distributor" == "Oracle" ]; then
		if [ -f /etc/redhat-release ]; then
			cp /etc/redhat-release $TmpDataPath >> $PCLog 2>tmp.err
			RETVAL=$?; 	printbothlog "cp /etc/redhat-release"
		fi

		if [ -f /etc/oracle-release ]; then
			cp /etc/oracle-release $TmpDataPath >> $PCLog 2>tmp.err
			RETVAL=$?; 	printbothlog "cp /etc/oracle-release"
		fi
		
		cp /boot/grub/grub.conf $TmpDataPath >>  $PCLog 2>tmp.err
		RETVAL=$?; 	printbothlog "cp /boot/grub/grub.conf"
	fi
}


# Collect /proc directory (partly)
CollectProcDir() {

	if [ -d $TmpDataPath/proc ]; then
		echo " Directory existing: "$TmpDataPath/proc
	else
		mkdir $TmpDataPath/proc
		echo " Create directory: "$TmpDataPath/proc
	fi

	cd $TmpDataPath

	# /proc/acpi
	# don't collect /proc/acpi if acpi daemon doesn't exist
		which acpid 1>acpidpath   2>/dev/null
		if [ $? -eq 0 ]; then
			# don't collect /proc/acpi if acpi daemon isn't started
			pidof `more acpidpath` > /dev/null 2>&1
			if [ $? -eq 0 ]; then
				CollectSingleDir /proc/acpi
			else
				printboth "acpi daemon not started"
				printboth "Collecting directory: /proc/acpi                : SKIP"
				echo " " 
			fi
		else
			printboth "acpi daemon not found"
			printboth "Collecting directory: /proc/acpi                : SKIP"
			echo " " 
		fi
		rm $TmpDataPath/acpidpath > /dev/null 2>&1		

	CollectSingleDir /proc/bus
	CollectSingleDir /proc/driver
	CollectSingleDir /proc/fs
	CollectSingleDir /proc/ide
	CollectSingleDir /proc/irq
	CollectSingleDir /proc/mpt
	CollectSingleDir /proc/net
	CollectSingleDir /proc/scsi
	CollectSingleDir /proc/self
	CollectSingleDir /proc/sysvipc
	CollectSingleDir /proc/tty
}
	
# Collect a single directory and it's subdirectories
# Start path is given by $1
# Collect files to $TmpDataPath$1/
CollectSingleDir() {
	printboth "Collecting directory: $1    ..."
	if [ -d $TmpDataPath$1 ]; then
		dprint "Directory existing : $TmpDataPath$1"
	else
		mkdir $TmpDataPath$1
		dprint "Create directory: $TmpDataPath$1"
	fi

	cp -v -r $1 $TmpDataPath$1 >>  $PCLog 2>tmp.err
	RETVAL=$?; 	printbothlog "    "
	echo " " 
}
	
# Collect a single directory and it's subdirectories
# Start path is given by $1
# Result path is given by $2
# Collect files to $TmpDataPath$2/
CollectSingleDir2() {
	printboth "Collecting directory: $1    ..."
	if [ -d $TmpDataPath$2 ]; then
		dprint "Destination directory existing : $TmpDataPath$2"
	else
		mkdir $TmpDataPath$2
		dprint "Create destination directory: $TmpDataPath$2"
	fi

	cp -v -r $1 $TmpDataPath$2 >>  $PCLog 2>tmp.err
	RETVAL=$?; 	printbothlog "    "
	echo " " 
}
	
# zipFile - zip or tar and gzip a file or a directory
#	if exists use zip otherwise tar and gzip to
#	compress a file or directory
# $1	name of the compressed file
# $2	source file or directory
# return the of the zip or gzip command

zipFile() {
	printboth "Compress directory or file: $2    ..."
	
	tmp=$(type zip 2>&1)
	if [ $? -eq 0 ]; then
		zip -r -v $TmpDataPath/$1 $2 >>  $PCLog 2>tmp.err
		RETVAL=$?
	else
		tar -cvf $TmpDataPath/$1.tar $2 >>  $PCLog 2>tmp.err && gzip $TmpDataPath/$1.tar >>  $PCLog 2>tmp.err
		RETVAL=$?
		
	fi
	
	printbothlog "    "
	echo " "
}
	
# check a single directory and it's subdirectories
# for : in filname; replace : to _ (windows compatible)
# Start path is given by $1
# Check directory $TmpDataPath$1/
CheckDir() {
	printboth "Directory: $TmpDataPath$1"
	printboth "Checking for invalid Windows filenames ..."
	if [ -d $TmpDataPath$1 ]; then
		dprint "Directory existing : $TmpDataPath$1"
		
		find $TmpDataPath$1 -name *:* > TmpList
		for ORIG in $(cat TmpList); do
			NEW=${ORIG//:/_}
			mv "$ORIG" "$NEW" >>  $PCLog 2>tmp.err
			RETVAL=$?; 	
			printboth "Move: $ORIG"
			printboth "To:   $NEW"
			printboth " "
		done
		if [ -f TmpList ]; then
			rm TmpList
		fi
		if [ -f tmp.err ]; then
			rm tmp.err
		fi
		
		RETVAL=0; 	printbothlog "    "
	else
		dprint "Directory not found: $TmpDataPath$1"
		RETVAL=1; 	printbothlog "    "
	fi

	echo " " 
}

# Archive and gzip Temp Directory
# Write .tgz archive to $DataPath
# Resulting archive: PrimeCollect_Data_YYYY_MM_DD_HHMMSS.tgz
ArchiveTempDir() {
	local fileExt

	cd $TmpDataPath
	# File Timestamp
		DATETIME=`LC_ALL=C date "+%Y_%m_%d_%H%M%S"`
	# SV File UTC Timestamp
		UTCSTAMP=`date --utc +%s`
		
	export PrimeCollectArchive=$DataPath/PrimeCollect_Data_$DATETIME
	
	tmp=$(type zip 2>&1)
	if [ $? -eq 0 ]; then
		fileExt="zip"
		zip -r  $PrimeCollectArchive $TmpDataPath >> $PCLog 2>tmp.err
		RETVAL=$?
	else
		fileExt="tar.gz"
		tar -cvf $PrimeCollectArchive.tar $TmpDataPath >>  $PCLog 2>tmp.err && gzip $PrimeCollectArchive.tar >> $PCLog 2>tmp.err
		RETVAL=$?
		
	fi	
	
	printboth "Archive temporary data to :"
	printboth "$PrimeCollectArchive.$fileExt"
	printbothlog " "
	#create symbolic link for PrimCollect Provider
		rm -f $SVDATAFILE  > /dev/null 2>&1
		ln -s "$PrimeCollectArchive.$fileExt" $SVDATAFILE

	if [ -f tmp.err ]; then
		rm tmp.err
	fi

}


##############################################################################
#  main 
##############################################################################

clear
#umask 0177

VERBOSE=0
STANDALONE=0

while getopts hHsSvV optChar; do
	case "$optChar" in
	H|h|[?])
		printf "PrimeCollect Vers:$SVER\n Usage:\n   [-V Verbose]\n   [-H This message]\n"
		exit 0
		;;
	S|s)
		STANDALONE=1
		echo "Running in Standalone Mode"
		echo " "
		;;
	V|v)
		VERBOSE=1
		echo "Running in Verbose Mode"
		echo " "
		;;
	esac
done
shift $(($OPTIND - 1))

# check if we are running as root
ChkContext

# check for another instance of PrimeCollect running
ChkOtherInst

# check for Temp Directory existing and delete content
CleanTmpDir

# delete symbolic link for PrimCollect Provider
rm -f $SVDATAFILE  > /dev/null 2>&1

# Create data directory
CreateDataPath

# Initialize Provider File
InitSVFile

# Set Progress to 1% in Provider File to avoid Collect button in Frontend
PROGRESS=1
UpdateSVFile

#add path variable /sbin
PATH=$PATH:/sbin

cd $TmpDataPath

title


printHeaderBoth "Check ServerView agents / Mode context"
CheckSVAgents

printHeaderBoth "Set function library path"	
SetFunctionPath

printHeaderBoth "Check distribution"	
CheckDistrib

printHeaderBoth "Check if we are running in a VM context"
CheckVM

printHeaderBoth "Collect data using own tools (part 1)"
RunTools_1
printspace "After collecting data with own tools (part 1)"

printHeaderBoth "Collect support relevant files (part 1)"
Collectfiles_1
printspace "After collecting \"support relevant \" files (part 1)"

printHeaderBoth "Collect /var/log/srvmagt directory"
zipFile "var_log_srvmagt" "/var/log/srvmagt"
printspace "After collecting directory \"/var/log/srvmagt\""

printHeaderBoth "Collect /var/log/fujitsu/ServerViewSuite/SCS directory"
zipFile "var_log_fujitsu" "/var/log/fujitsu/ServerViewSuite/SCS"
printspace "After collecting directory \"/var/log/fujitsu/ServerViewSuite/SCS\""

# printHeaderBoth "Collect /var/log/fujitsu/ServerViewSuite/vme directory"
# zipFile "var_log_fujitsu" "/var/log/fujitsu/ServerViewSuite/vme"
# printspace "After collecting directory \"/var/log/fujitsu/ServerViewSuite/vme\""

printHeaderBoth "Collect /proc files"
CollectProcDir
CheckDir /proc
printspace "After collecting directory \"/proc\" (partly)"

printHeaderBoth "Collect data using distributor tools"
RunDistribTools
printspace "After collecting data with distributor tools"

printHeaderBoth "Collect data using own tools (part 2)"
RunTools_2
printspace "After collecting data with own tools (part 2)"

printHeaderBoth "Collect /etc/srvmagt directory"
zipFile "etc_srvmagt" "/etc/srvmagt"
printspace "After collecting directory \"/etc/srvmagt\""

# PSA integration: MCO (only on PRIMEQUEST)
if [ -f /opt/fujitsu/SVmco/sh/getosvmco ]; then
	printHeaderBoth "Collect MCO data"
	CollectMCOdata
	printspace "After collecting MCO data"
fi

printHeaderBoth "Collect data using standard tools"
CollectStdTools
printspace "After collecting data with standard tools"

printHeaderBoth "Create result data archive"
ArchiveTempDir

# Print logfile to console (verbose mode)
ShowLog

# List temp directory to console (verbose mode)
ShowTempDir

echo "++++++++++++++++++++++++++++++++++++++++++++++++++++++"
echo "+ Removing temporary data"
echo "++++++++++++++++++++++++++++++++++++++++++++++++++++++"
CleanTmpDir

# Standalone mode only
if [ $STANDALONE -eq 1 ]; then
	CleanStandAloneDir
fi

# Release Lock directory
Unlock

TurnOnCron

echo `LC_ALL=C date "+%F-%T"`: Progress= 100%;
PROGRESS=100
UpdateSVFile


dprint "Total steps found: $STEP"
echo " "
echo " "
echo " "
echo "++++++++++++++++++++++++++++++++++++++++++++++++++++++"
echo "+ PrimeCollect finished normally"
echo "+"
echo "+ Result data archive:"
echo "+ $PrimeCollectArchive.$zipFileExt"
echo "++++++++++++++++++++++++++++++++++++++++++++++++++++++"

exit 0
# EOF

