#!/bin/bash
#
# Manage the Symantec autoprotect modules
#
# chkconfig: 235 21 95
# description: Symantec AutoProtect Modules
#
### BEGIN INIT INFO
# Provides:    autoprotect
# Required-Start: $syslog
# Required-Stop: $syslog
# Default-Start: 2 3 5
# Default-Stop:
# Description: Symantec AutoProtect Modules
### END INIT INFO

# Source function library (this should not be used as it doesn't
# exist on SuSE systems)
if [ -f /etc/init.d/functions ]
then
	. /etc/init.d/functions
fi

# Check permissions
if [ "`id -u`" != '0' ]; then
  echo 'Error: you must be superuser.'
  exit 1
fi

symconf=/etc/Symantec.conf
symbasedir=`grep BaseDir= /etc/Symantec.conf | awk -F"=" '{print $2}'`
devnode=/dev/symap
procfile=/proc/symap

#config_retpoline=`grep 'CONFIG_RETPOLINE=y' /boot/config-$(uname -r) | awk -F"=" '{print $2}'`

#echo 'CONFIG_RETPOLINE='$config_retpoline

# read config to get basedir
if [ -f $symconf ]
then
    ndir=`/bin/awk -v IGNORECASE=1 -F= '/^basedir=/ {print $2}' < $symconf`
    if [ -n "$ndir" -a -d "$ndir" ]
    then
	symbasedir=$ndir
    fi
fi

moduledir=$symbasedir/autoprotect

# syslog helper -- log to syslog or stderr if not possible
log() {
        PATH=/bin:/usr/bin type -p logger > /dev/null 2>&1 \
	    && PATH=/bin:/usr/bin logger -s -p kern.$1 -t $2 $3 \
	    && return 0
	echo $2: $3 >&2
}

# default module file suffix (.o is used on 2.4.x kernels)
modsuff=.ko

# find other potential matches for the current running kernel, in case
# we don't have an exact match available
# $1 is the target, $2 is the pattern to try
findfuzz() {
	/bin/ls $2 2>/dev/null | /bin/sort -r -n -t- -k1 -k2 -k3 -k4 -k5 -k6 -k7 | /bin/sed -e 's/^.*\///'
}

find_module() {
	case `/bin/arch` in
	i686)
		arch=(i686 i386)
		;;
	*)
		arch=(`/bin/arch`)
		;;
	esac

        archstr=`/bin/arch`
        kver=`/bin/uname -r | /bin/sed -e 's/\.'$archstr'//'`

	if [ -f /etc/fedora-release ]
	then
	    osvnd=fc
            kver=`/bin/uname -r | /bin/sed -e 's/\.PAE/PAE/' | /bin/sed -e 's/\.'$archstr'//'`
	    vstr=`cat /etc/fedora-release`
	    case $vstr in
		Fedora\ release\ 10*) osprod=ST osver=10 ;;
		Fedora\ release\ 11*) osprod=ST osver=11 ;;
		Fedora\ release\ 12*) osprod=ST osver=12 ;;
		Fedora\ release\ 13*) osprod=ST osver=13 ;;
		Fedora\ release\ 15*) osprod=ST osver=15 ;;
		Fedora\ release\ 16*) osprod=ST osver=16 ;;
		Fedora\ release\ 17*) osprod=ST osver=17 ;;
		Fedora\ release\ 18*) osprod=ST osver=18 ;;
		*) osprod=UNK osver=UNK ;;
	    esac
	elif [ -f /etc/oracle-release -a ${kver: -3} = "uek" ]
	    then
	    osvnd=or
	    vstr=`cat /etc/oracle-release`
	    case $vstr in
	        *Oracle\ Linux\ Server\ release\ 5*) osprod=uek osver=5 ;;
	        *Oracle\ Linux\ Server\ release\ 6*) osprod=uek osver=6 ;;
		*) osprod=UNK osver=UNK ;;
	    esac
	elif [ -f /etc/centos-release ]
		then
		# it's CentOS -- which kernel?
		osvnd=ct
			kver=`/bin/uname -r | /bin/sed -e 's/\.PAE/PAE/' | /bin/sed -e 's/\.'$archstr'//'`
		vstr=`cat /etc/centos-release`
		case $vstr in
			*CentOS\ release\ 6*) osprod=ES osver=6 ;;
			*CentOS\ Linux\ release\ 7*) osprod=ES osver=7 ;;
			*) osprod=UNK osver=UNK ;;
		esac
	elif [ -f /etc/redhat-release -a ! -f /etc/vmware-release ]
	    then
	    # it's redhat -- which kernel?
	    osvnd=rh
            kver=`/bin/uname -r | /bin/sed -e 's/\.PAE/PAE/' | /bin/sed -e 's/\.'$archstr'//'`
	    vstr=`cat /etc/redhat-release`
	    case $vstr in
		*Linux\ release\ 9*) osprod=LI osver=9 modsuff=.o ;;
		*Linux\ Advanced\ Server\ release\ 2.1*) osprod=AS osver=2.1 modsuff=.o ;;
		*Linux\ Enterprise\ Server\ release\ 2.1*) osprod=EL osver=(21ES 21AS) modsuff=.o ;;
		*Enterprise\ Linux\ AS\ release\ 3*) osprod=(AS ES) osver=3 modsuff=.o ;;
		*Enterprise\ Linux\ ES\ release\ 3*) osprod=ES osver=3 modsuff=.o ;;
		*Enterprise\ Linux\ WS\ release\ 3*) osprod=(WS ES) osver=3 modsuff=.o ;;
		*Enterprise\ Linux\ AS\ release\ 4*) osprod=(AS ES) osver=4 ;;
		*Enterprise\ Linux\ ES\ release\ 4*) osprod=ES osver=4 ;;
		*Enterprise\ Linux\ WS\ release\ 4*) osprod=(WS ES) osver=4 ;;
		*Desktop\ release\ 4*) osprod=(DS ES) osver=4 ;;
		*Enterprise\ Linux\ *\ release\ 5*) osprod=ES osver=5 ;;
		*Enterprise\ Linux\ *release\ 6*) osprod=ES osver=6 ;;
		*Enterprise\ Linux\ *release\ 7*) osprod=ES osver=7 ;;
		*Enterprise\ Linux*) osprod=EL osver=UNK ;;
		*) osprod=UNK osver=UNK ;;
	    esac
	elif [ -f /etc/SuSE-release ]
	then
	    # it's SuSE -- which kernel?
	    osvnd=su
	    vstr=`cat /etc/SuSE-release`
	    case $vstr in
		*Linux\ Desktop\ 9\ *) osprod=(LD ES) osver=9 ;;
		*Enterprise\ Server\ 9\ *) osprod=(ES LD) osver=9 ;;
		*Linux\ Enterprise\ *\ 10\ *) osprod=LE osver=10 ;;
		*Linux\ Enterprise\ *\ 11\ *) osprod=LE osver=11 ;;
		*Linux\ 9.1\ *) osprod=ES osver=9.1 ;;
		*) osprod=UNK osver=UNK ;;
	    esac
	else
	    ## Versions that need more code to detect
	    # Detect VMware ESX
	    if [ -x /usr/bin/vmware ]
	    then
		# any VMware version installs /usr/bin/vmware, so we need to run
		# it and make sure this is an ESX installation
		vnum=`/usr/bin/vmware -v`
		case $vnum in
		    *ESX\ Server\ 3*) osvnd=vw osprod=(ESX) osver=3 modsuff=.o ;;
		    *ESX\ Server\ 2*) osvnd=vw osprod=(ESX) osver=2 modsuff=.o ;;
		    *ESX\ Server*) osvnd=vw osprod=(ESX) osver=UNK modsuff=.o ;;
		    *) osprod=UNK osver=UNK ;;
		esac

		if [ "$osvnd" = vm ]
		then
		    # ESX kernels may need build number for disambiguation
		    bnum=`/usr/bin/vmware -v | /bin/sed -e 's/^.*build-//'`
		    if [ $? -eq 0 -a -n "$bnum" ]
		    then
			arch=($bnum-i686 $bnum-i386)
		    fi
		fi
	    else
		# defaults - unidentified system
                osvnd=UNK
		osprod=UNK 
		osver=UNK
	    fi
	fi

	# base kernel version (for fuzzy matching)
	if [ $osvnd = "rh" ] || [ $osvnd = "fc" ]
	then
	    # Add RHEL3-x86_64 on Intel EM64T support 
	    if [ $osvnd = "rh" -a $osver = "3" -a $arch = "x86_64" ]
	    then
		if grep "model name" /proc/cpuinfo | grep -i Intel > /dev/null 2>&1
		then
	            kver=${kver}ia32e
		fi
	    fi
	    kverpatt=`echo $kver | sed -e 's/-[^a-zA-Z]*/-*/'`
        elif [ $osvnd = "su" -a $osprod = "LE" -a $osver = "11" ] # SLES 11 series
        then
            kverpatt=`echo $kver | sed -e 's/-[^-]*/-*/' | sed -e 's/[0-9][0-9]-/*-/'`
	else
	    kverpatt=`echo $kver | sed -e 's/-[^-]*/-*/'`
	fi
	fuzzy1=
	fuzzy2=
	fuzzy3=
	totry=
	
	# try all the combos determined above till we find one we actually have
	# also find "fuzzy" (close) match candidates that would be worth trying
	
	# Spectre2 Mitigation supported kernels (like  RHEL6/7 3.10.0-693.21.1), are built with config_retppoline aware compilers.
	# kernel modules also need to be compiled with config_retpoline, if not results in kernel panic.
	# sep uses crosstool-ng cross compiler to build AP kernel modules
	# at this point of time crosstool-ng does not support gcc 7/8 that config_retpoline
	# with this condition autoprotect startup script will not load pre-built modules.
	# 'custom' modules are built on the target machines with gcc and config_retpoline param. 
#	if [ "$config_retpoline" != "y" ]
#	then
	for vnd in ${osvnd[@]}; do
		for prd in ${osprod[@]}; do
			for ver in ${osver[@]}; do
				for arc in ${arch[@]}; do
					modname=$1-$vnd-$prd-$ver-$kver-$arc$modsuff
					totry=(${totry[*]} $modname)
 					fuzzy1=(${fuzzy1[*]} `findfuzz $moduledir/$modname "$moduledir/$1-$vnd-$prd-$ver-$kverpatt-$arc$modsuff"`)
 					fuzzy2=(${fuzzy2[*]} `findfuzz $moduledir/$modname "$moduledir/$1-$vnd-$prd-*-$kver-$arc$modsuff"`)
 					fuzzy2=(${fuzzy2[*]} `findfuzz $moduledir/$modname "$moduledir/$1-$vnd-$prd-*-$kverpatt-$arc$modsuff"`)
 					fuzzy3=(${fuzzy3[*]} `findfuzz $moduledir/$modname "$moduledir/$1-$vnd-*-$ver-$kver-$arc$modsuff"`)
 					fuzzy3=(${fuzzy3[*]} `findfuzz $moduledir/$modname "$moduledir/$1-$vnd-*-$ver-$kverpatt-$arc$modsuff"`)
				done
			done
		done
	done
#	else
#		echo "kernel built with config_retpoline, skipping fuzzy matching logic so that we dont load pre-compiled AP kernel modules"	
#	fi

	custommodname=$1-custom-`/bin/uname -r | /bin/sed -e 's/\.PAE/PAE/' | /bin/sed -e 's/\.'$archstr'//'`-`/bin/uname -m`$modsuff
	echo ${custommodname} ${totry[*]} ${fuzzy1[*]} ${fuzzy2[*]} ${fuzzy3[*]} UNSUPPORTED-OS-$osvnd-$osprod-$osver-$kver-$arc
	return 0
}

# check if the module file should be loaded.
# we only try loading module file whose version <= local OS kernel version
check_module() {
	# don't check VMware ESX 2 platform
	if /bin/uname -r | grep "vmnix2" > /dev/null 2>&1
	then
		return 0
	fi

	# if kernel base version is different, skip check. e.g. SLES 11 series 
        checkbaseversion=`echo $1 | awk -F- '{print$5}'`
        localbaseversion=`/bin/uname -r | awk -F- '{print$1}'`
        if [ $checkbaseversion != $localbaseversion ]
        then
                return 0;
        fi

	# get module file non-base kernel version (the 6th sect)
	# e.g. symap-rh-ES-4-2.6.9-22.EL-i686.ko -> '22.EL'
	checkversion=`echo $1 | awk -F- '{print$6}'`
	# get local OS non-base kernel version (the 2th sect)
	# e.g. 2.6.9-55.ELhugemem -> '55.ELhugemem'
	localversion=`/bin/uname -r | awk -F- '{print$2}'`

	chesect=0
	locsect=0
	loop=1
	loopflag=0
	res=0

	while :
	do
		cmdstr=`echo "{print $""${loop}}"`
		# get each sect in non-base kernel version
		chesect=`echo $checkversion | awk -F. "$cmdstr"`
		locsect=`echo $localversion | awk -F. "$cmdstr"`

		# check if the sect is null
		if [ -z $chesect ]
		then
			chesect=-1
			loopflag=1
		fi

		if [ -z $locsect ]
		then
			locsect=-1
			loopflag=1
		fi

		# check if the sect is number
		expr $chesect + 1 > /dev/null 2>&1
		if [ $? -ne 0 ]
		then
			chesect=-1
			loopflag=1
		fi
		
		expr $locsect + 1 > /dev/null 2>&1
		if [ $? -ne 0 ]
		then
			locsect=-1
			loopflag=1
		fi

		# compare the sect value
		if [ $locsect -gt $chesect ]
		then
			res=0
			loopflag=1
		fi

		if [ $chesect -gt $locsect ]
		then
			res=1
			loopflag=1
		fi

		# check if should end loop and return
		if [ $loopflag -eq 1 ]
		then
			return $res
		fi
		
		loop=`expr $loop + 1`
	done
}

# Find the right module file, load it, and check to make sure
# it loaded OK.  Or NOP if the module is already loaded.
# $1 module file name.
# $2 module name if exits.
find_and_load_module() {
    [ -f /proc/$1 ] && {
	echo $1 already loaded.
	return 0
    }

	local kerneldir="/lib/modules/$(uname -r)/kernel/drivers/char"

    modlist=(`find_module $1`)

    for mod in ${modlist[*]}; do
	if [ -f $moduledir/$mod ]; then
	    if check_module $mod > /dev/null 2>&1 ; then
	        /sbin/insmod $moduledir/$mod && {
		    # double-check
			local modname="$1"
			if [ ! "$2" = "" ] ; then
				modname="$2"
			fi

		    [ -f /proc/$modname ] || {
		        log err $modname "kernel support init failed ($mod)"
		        return 1
		    }
		    log info $modname "loaded ($mod)"
			
			#check to see if the sep modules have links in /lib/modules/$(uname -r)/kernel/drivers/char
			#it is needed for cases when kernel is upgraded after SEPFL is installed and services like kdump/mkdumprd 
			#are failing to locate the symap & symev modules loaded in to kernel from SEPFL installation folder

			local tempmodfile=$(echo $mod | sed -e 's/\.ko//g' -e 's/\./-/g' -e 's/_/-/g')

			if [ ! -f $kerneldir/$tempmodfile.ko ] ; then

				echo "$kerneldir/$tempmodfile.ko does not exist, need to create link"

				ln -s $moduledir/$mod $kerneldir/$tempmodfile.ko

				if [ 0 -eq $? ] ; then
					echo "succeeded to create link $kerneldir/$tempmodfile"
				else
					echo "failed to create link $kerneldir/$tempmodfile, err: $?"
				fi
			else
				echo "$kerneldir/$tempmodfile.ko exists, no need to create link"
			fi

		    return 0
	    	}
	    fi
	fi
    done

    log err $1 "unable to load kernel support module ($mod)"
    return 1
}

# find our module, verify it's idle, and rmmod it
# -- module not loaded is also success
stop_running_module() {
    modname=$1
    # get module status
    status=(`/sbin/lsmod | grep "^$modname[-_]"`)
    if [ $? -ne 0 ]
    then
	# not found
	log err $1 "not currently loaded"
	return 0
    fi

    # 2.4:
    # symap-rh-ES-3-2.4.21-4.EL   22028   1   
    # symev-rh-ES-3-2.4.21-4.EL   26080   1   [symap-rh-ES-3-2.4.21-4.EL]
    # 2.6:
    # symap_su_ES_9_2_6_5_7_97_smp_i386   22028   2   
    # symev su_ES_9_2_6_5_7_97_smp_i386   26080   1   symap_su_ES_9_2_6_5_7_97_smp_i386

    rmodname=${status[0]}
    usecount=${status[2]}

    # ensure use count is zero
    [ $usecount -ne 0 ] && {
	log err $1 "module in use ($modname: count=$usecount)"
	return 1
    }

    echo Unloading $modname as $rmodname
    /sbin/rmmod $rmodname || {
	log err $1 "rmmod failed ($modname)"
	return 1
    }

    return 0
}

# ensure /dev/symap exists and contains the right node numbers.
# We get the info from /proc/symap if possible, then confirm it
# by reading the node
update_dev_symap() {
    major=254

    if [ -f $procfile ]
    then
	dstr=`/bin/awk -F= '/^devmajor=/ {print $2}' < $procfile 2> /dev/null`
	if [ -n "$dstr" ]
	then
	    if [ $dstr -gt 0 -a $dstr -le 255 ]
	    then
		echo Setting major=$dstr from $procfile
		major=$dstr
	    else
		echo "Using default major=$major (bad devmajor in $procfile)"
	    fi
	else
	    echo "Using default major=$major (no devmajor in $procfile)"
	fi
    else
	echo "Using default major=$major (no $procfile)"
    fi

    # delete the node if it exists already, then (re)-make it
    # (ignore errors -- we'll make sure module is responding below)
    /bin/rm -f $devnode
    /bin/mknod $devnode c $major 0

    # read from the node, make sure the module is responding
    out=`cat $devnode`
    if [ "$?" -eq 0 -a -c "$devnode" ]
    then
	# make sure we get the expected response
	nstr=`/bin/awk -F= '/^symap=/ {print $2}' < $devnode 2> /dev/null`
	if [ "$nstr" -ne "$major" ]
	then
	    log err symap "$devnode is not responding correctly"
	    return 1
	fi

	return 0
    fi

    log err symap "$devnode has not been created correctly"
    return 1
}

# ensure /dev/symap exists and contains the right node numbers.
# We get the info from /proc/symap if possible, then confirm it
# by reading the node
status() {
    if [ ! -e $devnode ]
    then
	echo "$devnode: does not exist"
	return 1
    fi

    if [ ! -c $devnode ]
    then
	echo "$devnode: invalid node"
	return 1
    fi

    # read from the node, make sure the module is responding
    out=`cat $devnode`
    if [ $? -eq 0 ]
    then
	# make sure we get the expected response
	nstr=`/bin/awk -F= '/^symap=/ {print $2}' < $devnode 2> /dev/null`
	if [ "$nstr" -gt 0 -a "$nstr" -le 255 ]
	then
	    echo OK
	    return 0
	fi

	echo "$devnode: bad response"
	return 1
    fi

    echo "$devnode: no response"
    return 1
}

start() {
	echo -n $"Starting AP: "
	# Check, find and load the modules
	# Check and adjust the /dev/symap node
	find_and_load_module symev && 
	find_and_load_module symap &&
	update_dev_symap &&
	return 0

	return 1
}

stop() {
	echo -n $"Stopping AP: "
	stop_running_module symap &&
	return 0

	return 1
}

findm() {
	echo -n $"Finding AP modules: "
	# Check, find and load the modules
	find_module symev
	find_module symap
	return 0
}

remove(){
	#check, find and load the symevrm modules to remove the symev and symap.
	#symevrm will be unloaded from kernel after it removes the symev and symap.
	find_and_load_module ".symevrm" "symevrm" &&
	stop_running_module symevrm &&
	return 0

	return 1
}

restart() {
	stop
	start
}	

reload() {
	restart
}	

case "$1" in
start)
	start
	;;
stop)
	stop
	;;
reload|restart)
	restart
	;;
condrestart)
        restart
	;;
find)
	findm
	;;
status)
	status
	;;
remove)
	remove
	;;
*)
	echo "Usage: $0 {start|stop|restart|condrestart|status}"
	exit 1
esac

exit $?
