#!/bin/sh
# $Copyright$
# Copyright (C) Fujitsu Technology Solutions 2009, 2010, 2011, 2012, 2013, 2014
# All rights reserved
#
# $Copyright$
# Copyright (C) Fujitsu Siemens Computers GmbH 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009
# All rights reserved
#############################################################################
#
# eecd:		ServerView Agent Linux Environment and Enclosure Control
#               Daemon init script. The eecd daemon takes care of handling
#               enclosure control data such as overtemperature or fan failures.
#
# chkconfig: 2345 57 21
# processname: eecd
# description: Starts and stops the eecd daemon
#
### BEGIN INIT INFO
# Provides: eecd
# Required-Start: $local_fs $network $syslog eecd_mods +aurad
# Should-Start:
# Required-Stop:
# Default-Start: 2 3 5
# Default-Stop: 0 1 6
# Description: Starts and stops the eecd daemon
### END INIT INFO
#


#
# Exit status codes (see LSB 3 spec, ch. 20) are :
# 0     OK
# 1     generic or unspecified error
# 2     invalid or excess argument(s)
# 3     unimplemented feature (e.g. "reload")
# 4     user had insufficient privileges
# 5     program is not installed
# 6     program is not configured
# 7     program is not running
# 8+    reserved (see LSB Core Spec 3.1, ch. 20)

# Set up a decent path.
PATH="/sbin:/usr/sbin:/bin:/usr/bin"
export PATH


# Use LSB function library for convenience.

[ -f /lib/lsb/init-functions ] && . /lib/lsb/init-functions

# Source ServerView function library

. /etc/srvmagt/config
. /etc/srvmagt/functions
exportConfVars

[ "$1" = stop ] &&  {
    # Do not stop an already stopped eecd daemon

    pid=$(mypidof "/usr/sbin/eecd") || {
        mylog_success_msg "Shutting down ServerView service eecd (not running)"
        exit 0
    }

    # Stop the daemon. This SHOULD use LSB killproc.
    # Try SIGTERM first and have patience ...; then use SIGKILL
    # and clear susystem ready

    killsig=TERM
    kill -TERM $pid

    echo -e "Shutting down ServerView service eecd ..\c"
	WaitForEecdTerm=${WaitForEecdTerm:-90}
	count=${count:-$WaitForEecdTerm}    # If >99 adjust \b's below
	while [ $count -gt 0 ]; do
		sleep 1
		pid=$(mypidof "/usr/sbin/eecd") || break
		count=$(($count - 1))
		if [ $count -ge 10 ]; then
			echo -e "\b\b$count\c"
		else
			echo -e "\b\b$count \c"
		fi
	done
	echo -e "\r\c"

	if [ "$pid" ]; then
		killsig=KILL
		kill -KILL $pid
	fi

	if [ "$killsig" = "TERM" ]; then
		mylog_success_msg "Shutting down ServerView service eecd: $killsig"
		rm -f /var/lock/subsys/eecd
		exit 0
	else
		mylog_failure_msg "Shutting down ServerView service eecd: $killsig"
		rm -f /var/lock/subsys/eecd
		exit 1
	fi
}

# perform SetSvEnv only if not yet done
[ -z "$SV_NICKNAME" ] && SetSvEnv

#

case "$1" in
start|trace|rescan)
    case "$1" in
    trace|traceall) flags="$2"
                    TraceFileLimit=0
                    export SV_LOG_DEBUG_LEVEL=255
                    ;;
    rescan)         flags="-rescan" ;;
    start)          flags="$2"
                    [ "$TraceFileLimit" = "0" ] && export SV_LOG_DEBUG_LEVEL=0
                    ;;
    *)              flags= ;;
    esac

    umask 0066
    # exit if OpenIPMI should be loaded at RHEL4 on x86_64
    
	lsmod | grep -q 'ipmi_' && [ "$SV_NICKNAME" = "RHEL4"  ] && {
		mylog_failure_msg "Starting ServerView service eecd: use ServerView IPMI on $SV_NICKNAME"
		exit 1
    }

    # Write a message to syslog if no kernel modules are loaded
    
	lsmod | egrep -q 'ipmi|smbus'
	[ $? -eq 1 ] && logger -p daemon.notice  -t $MYNAME "Starting ServerView service eecd: kernel modules ipmi and smbus not loaded"
    
	# Do not restart an already running eecd daemon

	pid=$(mypidof "/usr/sbin/eecd") && {
		mylog_success_msg "Starting ServerView service eecd: already running $pid"
			exit 0
		}

    # Check whether ServerView-RAID service is installed and running

    SV_RAID_EXISTS=0
    SV_RAID_READY=0

     [ -x /etc/init.d/aurad ] || [ -f /usr/lib/systemd/system/svraid.service ] && {
        SV_RAID_EXISTS=1
        echo -e "Waiting until ServerView-RAID service is listening on port #3173 ..\c"
        count=30    # If >99 adjust \b's below
        while [ $count -gt 0 ]; do
            LC_ALL=C netstat -anp | egrep -q '[^0-9]3173[^0-9].*LISTEN.*amDaemon' && break
            sleep 1
            count=$(($count - 1))
            if [ $count -ge 10 ]; then
                echo -e "\b\b$count\c"
            else
                echo -e "\b\b$count \c"
            fi
        done

        SV_RAID_READY=1
        [ $count -eq 0 ] && {
            SV_RAID_READY=0
            echo " giving up after 30 seconds"
            echo "ServerView-RAID service is not listening. Continue anyway."
        }
        echo -e "\b\bdone ($count)"
    }
    export SV_RAID_EXISTS SV_RAID_READY

	# Check if InventoryRescan is specified in configuration file.
	#          0 =  no rescan after start scan
	#          N =  rescan every N minutes where 1 <= N <= 120 equals N = 120.
	#               Max. value = 24 days. Greater values are set to 0 (no rescan)


	[ -n "$InventoryRescan" ] &&  {
		# Check the value
		[ $InventoryRescan -gt 0 -a $InventoryRescan -lt 120 ] && InventoryRescan=120
		[ $InventoryRescan -gt 34560 ] && InventoryRescan=0
		
		#  Change value for RescanTime (minutes!) in EM_VINFO.ini and ScanTime (seconds!) in registry
		sed -i "s/^RescanTime=[0-9]*/RescanTime=$InventoryRescan/" /etc/srvmagt/EM_VINFO.ini
		RescanSeconds=$[$InventoryRescan*60]
		sed -i "s/^ScanTime=d=[0-9]*/ScanTime=d=$RescanSeconds/" /etc/srvmagt/registry
	}
    

	# Save the eecd daemon Logfiles in a gzip Tar archive
	( cd /var/log/srvmagt
	logFiles=$(find . -name log.eecd\*)
	[ -z "$logFiles" ] || tar -czf log.EecdLogs.tgz $logFiles )

	rm -f /var/log/log.eecd
	rm -f /var/log/srvmagt/log.eecd /var/log/srvmagt/log.eecd_[ab] /var/log/srvmagt/log.eecd_pciinfo

	# gather PCI information for diagnostic purposes
	echo "---- cat /proc/bus/pci/devices ----"         >  /var/log/srvmagt/log.eecd_pciinfo 2>/dev/null
	cat /proc/bus/pci/devices                          >> /var/log/srvmagt/log.eecd_pciinfo 2>/dev/null
	echo "---- ls -l /sys/bus/pci/devices ----"        >> /var/log/srvmagt/log.eecd_pciinfo 2>/dev/null
	ls -l /sys/bus/pci/devices                         >> /var/log/srvmagt/log.eecd_pciinfo 2>/dev/null
	echo "---- /proc/bus/pci/* ----"                   >> /var/log/srvmagt/log.eecd_pciinfo 2>/dev/null
	ls -l /proc/bus/pci/*                              >> /var/log/srvmagt/log.eecd_pciinfo 2>/dev/null
	echo "---- /sbin/lspci -vvvv ----"                 >> /var/log/srvmagt/log.eecd_pciinfo 2>/dev/null
	/sbin/lspci -vvvv                                  >> /var/log/srvmagt/log.eecd_pciinfo 2>/dev/null
	echo "---- /sbin/lspci -x ----"                    >> /var/log/srvmagt/log.eecd_pciinfo 2>/dev/null
	/sbin/lspci -x                                     >> /var/log/srvmagt/log.eecd_pciinfo 2>/dev/null

	# Remove eecd sockets
	rm -f /dev/eec /dev/eecd[as]

	[ ! -s /etc/srvmagt/registry ] && {
		mylog_success_msg "Warning: /etc/srvmagt/registry corrupt. Using backup."
		cp -p /etc/srvmagt/registry.old /etc/srvmagt/registry
	}

	grep -qF '[HKEY_CLASSES_ROOT]'  /etc/srvmagt/registry || {
		mylog_success_msg "Warning: /etc/srvmagt/registry corrupt.  Using backup."
		cp -p /etc/srvmagt/registry.old /etc/srvmagt/registry
	}

	# Get ServerView-RAID version info from amCLI command and export it. Usage
	# of rpm command has been removed because of SA 233452258 (six eecds) - KT
	# Added amCLI -v command for RAID versions >= V5.7.1. After that it will
	# now be retried 10 times to get the version with the old command because
	# the RAID database may not be initialised in time (SA 233484979) - KT

	SV_RAID_VERSION=""

	if [ $SV_RAID_EXISTS -eq 0 ]; then
		SV_RAID_VERSION="N/A"
	else
		result=`amCLI -v 2>/dev/null | grep -i 'amCLI v'`

		if [ $? -eq 0 ]; then
			SV_RAID_VERSION=${result#*amCLI v}
		else
			count=10
			while [ $count -gt 0 ]; do
				result=`amCLI -l 21/0 2>/dev/null | grep -i 'Version: '`
				if [ $? -eq 0 ]; then
					SV_RAID_VERSION=${result#*Version: }
					break
				else
					sleep 1
					count=$(($count - 1))
				fi
			done

			if [ $count -le 0 ]; then
				SV_RAID_VERSION="N/A"
				echo "Couldn't get ServerView Raid Version in time."
			fi
		fi
	fi
	export SV_RAID_VERSION

	# Start the daemon. This SHOULD use the LSB start_daemon routine.
	[ "$SV_DAEMON_COREFILE_LIMIT" = "" -o "$SV_DAEMON_COREFILE_LIMIT" = 0 ] ||
		ulimit -c $SV_DAEMON_COREFILE_LIMIT

# This path is needed to catch additional OEM libs for eecd
#if [ "$SV_ARCH" = "x86_64" -a "${SV_NICKNAME:0:4}" != "SLES" -a "${SV_NICKNAME:0:4}" != "RHEL" -o "$SV_NICKNAME" = "RHEL7" ]; then
if [ "$SV_ARCH" = "x86_64" -a "$SV_NICKNAME" = "RHEL7" ]; then
	LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/usr/lib/srvmagt:/opt/SMAW/RAID/bin:/opt/fsc/RAID/bin:/opt/fujitsu/ServerViewSuite/RAIDManager/bin:/etc/srvmagt/smtp/lib:/etc/srvmagt/UpdateBin/lib64
else
	LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/usr/lib/srvmagt:/opt/SMAW/RAID/bin:/opt/fsc/RAID/bin:/opt/fujitsu/ServerViewSuite/RAIDManager/bin:/etc/srvmagt/smtp/lib:/etc/srvmagt/UpdateBin/lib
fi
	export LD_LIBRARY_PATH
	export SV_USE_SNMPLIB=1
	export PSA_SV_HOME=/opt/fujitsu/ServerViewSuite/HWLog

	if [ "$SV_SYSTEM" = "suse" ]; then
		# create directory for syslog_fifo of HWLogFilter library, if necessary
		if [ ! -d /dev/HWLog ]; then
			mkdir /dev/HWLog
			chmod 0700 /dev/HWLog
		fi
		if [ ! -p /dev/HWLog/syslog_fifo ]; then	
			mkfifo -m 600 /dev/HWLog/syslog_fifo
			/sbin/service  syslog status && /sbin/service  syslog restart >/dev/null 2>/dev/null
			/sbin/service rsyslog status && /sbin/service rsyslog restart >/dev/null 2>/dev/null
		fi
		export PSA_SYSLOG_FIFO=/dev/HWLog
	else
		export PSA_SYSLOG_FIFO=/opt/fujitsu/ServerViewSuite/HWLog/path
	fi
	
	if [ "$SV_ARCH" = "x86_64" ]; then
		# Disable glibc internal allocator checks.
		# This is very ugly hack, but this allows daemons to start
		export MALLOC_CHECK_=0
	fi

	/usr/sbin/eecd $flags 2>/var/log/srvmagt/log.eecd >&2 </dev/null

	# Show formatted completion status and set subsystem ready
	if [ $? -eq 0 ]; then
		mylog_success_msg "Starting ServerView service eecd $flags"
		touch /var/lock/subsys/eecd
		exit 0
	else
		mylog_failure_msg "Starting ServerView service eecd $flags"
		rm -f /var/lock/subsys/eecd
		exit 1
	fi ;;

force-reload)
    # Reload configuration, if the service supports this,
    # otherwise start the service if it is not running

    pid=$(mypidof "/usr/sbin/eecd") || $0 start
    exit $? ;;

restart)
    $0 stop
    $0 start
    exit 0 ;;

status)
    # Status codes in this case are:
    # 0     service is running [OK]
    # 1     service is dead /var/run/<pid file> exists
    # 2     service is dead and /var/lock/<lock file> ecists
    # 3     service is not running
    # 4     service status is unknown
    # 5+    reserved (see LSB Core Spec 3.1, ch. 20)

    pid=$(mypidof "/usr/sbin/eecd")
    if [ $? -eq 0 ]; then
        statMsg=$(printf "Checking for ServerView service eecd: pid %s" $pid)
        rc=0
    else
        statMsg=$(printf "Checking for ServerView service eecd: stopped")
        rc=3
    fi
    echo $statMsg
    logger -t $MYNAME $statMsg
    exit $rc ;;

try-restart|reload|*)
    echo "Usage: $0 {start|trace|stop|restart|force-reload|status}"
    exit 1 ;;
esac

exit 1
# EOF
