#!/bin/sh
#
#    Copyright (c) 2007-2016 Brocade Communications Systems, Inc.
#    All rights reserved.
#
#    Description:
#
#		firmwarecheck CLI implementation.	
#

PATH=/bin:/usr/bin:/sbin:/usr/sbin
STS_OK=0
STS_ERR=255

# Check RBAC permission on command
/fabos/libexec/rbac_check `/bin/basename $0`

if [ $? -ne 0 ]; then
    exit 127
fi

if [ $# -gt 0 ] ; then
	echo -e "Usage:"
	echo -e "--help		Displays firmwarecheck command usage"
	echo -e " "
	echo -e "Run the command firmwarecheck without arguments to perform the integrity check on the files installed by RPM."
	exit $STS_ERR
fi


PLATFORM=`sin | \
		  /bin/grep Platform | \
	      /usr/bin/cut -d" " -f2 | \
		  /usr/bin/cut -d"," -f1`
			
echo -e "Validating integrity of firmware on root filesystem"
echo -e "Please wait..."

	VIOLATIONS=`rpm -Va --nodeps | grep "^.\{2\}5.\{6\} .\+$" | grep -v "^.\{11\}\(\/var\).\+$" | grep -v "ld-2.3.6.so\|ldconfig\|/fabos/share/release\|/usr/share/curl"`
    #
    # exclude /etc files from validations with the exception for the files /etc/profile,
    # /etc/fstab and files under /etc/rc.d/init.d/
    #
    EXCLUSIONS=`echo -e "$VIOLATIONS" | grep -v "^.\{11\}\(\/etc\|\/fabos\/man\/cat7\).\+$"`
	EXCEPTIONS=`echo -e "$VIOLATIONS" | grep "^.\{11\}\(\/etc\/profile\|\/fabos\/man\/cat7\/|\/etc\/fstab\|\/etc\/rc.d\/init.d\|\/etc\/fabos\/profile\|\/etc\/rc.d\/rc\)"`

	# 
	# exclude some files for specific platforms
	#
	if [ "$PLATFORM" = "SWBD167" ]; then
		EXCLUSIONS=`echo -e "$EXCLUSIONS" | grep -v "\(\/sbin\/poweroff\|\/usr\/bin\/poweroff\)"`
	fi

    if [ "$EXCLUSIONS" != "" -o "$EXCEPTIONS" != "" ]; then
        if [ "$EXCLUSIONS" != "" ]; then
            echo -e "$EXCLUSIONS"
        fi
        if [ "$EXCEPTIONS" != "" ]; then
            echo -e "$EXCEPTIONS"
        fi
		echo -e "Firmware integrity check failed."
		exit $STS_ERR
    fi
#
# Handle ldconfig and ld.so (shared loader) as a special case
#
	if [ "$PLATFORM" != "SWBD141" -a "$PLATFORM" != "SWBD142" -a "$PLATFORM" != "SWBD148" -a "$PLATFORM" != "SWBD171" -a "$PLATFORM" != "SWBD156" -a "$PLATFORM" != "SWBD161" -a "$PLATFORM" != "SWBD162" -a "$PLATFORM" != "SWBD165" -a "$PLATFORM" != "SWBD166" -a "$PLATFORM" != "SWBD169" -a "$PLATFORM" != "SWBD170" -a "$PLATFORM" != "SWBD172" -a "$PLATFORM" != "SWBD173" -a "$PLATFORM" != "SWBD178" ]; then
    	if [ ! -f /etc/ldchksum ]; then
			echo -e "GLIBC loader checksum not found"
			echo -e "Firmware integrity check failed."
			exit $STS_ERR
    	fi
    	LDCKSUMS=`/usr/bin/md5sum -c /etc/ldchksum`
    	if [ $? -ne 0 ]; then
			echo -e "$LDCKSUMS"
			echo -e "Firmware integrity check failed."
			exit $STS_ERR
    	fi
	fi
echo -e "Firmware integrity test passed."	
exit $STS_OK
