#!/bin/sh

# PROVIDE:	microcode_update
# REQUIRE:	root mountcritlocal
# KEYWORD:	nojail
# BEFORE:	SERVERS

#
# Add the following line to /etc/rc.conf to enable flow-capture:
# microcode_update_enable (bool):	Set it to "YES" to update microcode on startup
#					Set to "NO" by default.
# microcode_update_datadir (str):	Directory, microcode updates stored in.
#					Default is "%%DATADIR%%"
# microcode_update_cpus (str):		A list of cpus to update on startup, or "ALL" for all.
#					Example: microcode_update_cpus="0 1"
#					Set to "ALL" by default. 
# microcode_update_flags (str):		Flags for cpucontrol(8).

. /etc/rc.subr

name="microcode_update"
rcvar=microcode_update_enable
stop_cmd=":"
start_cmd="microcode_update_start"
required_modules="cpuctl"

CMT="/usr/sbin/cpucontrol"

microcode_update_start()
{
	echo "Updating CPU Microcode..."
	if [ "${microcode_update_cpus}" = "ALL" ]; then
		ncpu=`/sbin/sysctl -n hw.ncpu`
		cpus=`jot ${ncpu} 0`;
	else
		cpus=${microcode_update_cpus}
	fi
	for i in ${cpus}; do
		${CMT} -u ${microcode_update_flags} \
                    -d "${microcode_update_datadir}" /dev/cpuctl${i} 2>&1 | \
                    logger -p daemon.notice -t microcode_update || \
		    (echo "Microcode Update Failed." && exit 1)
	done
	if [ "${microcode_update_cpus}" = "ALL" ]; then
                CPUCONTROL_UPDATED=$(cpucontrol -h 2>&1 | grep -q -- -e; echo $?)
                if [ ${CPUCONTROL_UPDATED} -ne 0 ]; then
                        echo "Please update your system in order to update CPU microcode."
                else
			${CMT} -e /dev/cpuctl0 >/dev/null 2>&1
			if [ $? -ne 0 ]; then
				echo "Re-evalulation of CPU flags Failed."
				exit 1
			fi
                fi
	fi
	echo "Done."
}

load_rc_config $name

# Set default values
if [ -n "${microcode_cpus}" ]; then
	if [ -n "${microcode_update_cpus}" ]; then
		echo "Warning: Ignoring deprecated rc variable, microcode_cpus."
	else
		echo "Warning: rc variable microcode_cpus is deprecated.
Warning: Set microcode_update_cpus instead."
		microcode_update_cpus="${microcode_cpus}"
        fi
fi

: ${microcode_update_enable="NO"}
: ${microcode_update_datadir="%%DATADIR%%"}
: ${microcode_update_cpus="ALL"}
: ${microcode_update_flags=""}

run_rc_command "$1"
