#!/bin/sh

FIRMWARE_DIR=/usr/local/tsc
FIRMWARE_VER=${FIRMWARE_DIR}/version

# Only for startup
if [ "$1" != "start" ]; then
	exit 0
fi

# Skip if 'no_flash' is set in the kernel environment
if kenv | grep -q no_flash ; then
	exit 0
fi

# If there is no tsc package, don't do anything (but this shouldn't happen)
tsc_pkg=`pkg_info | grep twc_tsc`
if [ -z "${tsc_pkg}" ]; then
	exit 0
fi
if ! [ -r ${FIRMWARE_VER} ]; then
	exit 0
fi

# Extract the desired version from the firmware version file
firmware_ver=`cat /usr/local/tsc/version | sed -E 's/(.*)([0-9]+\.[0-9]+\.[0-9]+)(.*)/\2/'`

# Get the current firwmare from the driver
major=`sysctl -n hw.tsc.version.major`
minor=`sysctl -n hw.tsc.version.minor`
patch=`sysctl -n hw.tsc.version.patch`
current_ver="${major}.${minor}.${patch}"

# If there is no card or no firmware on the card, then don't do anything.
if [ "${current_ver}" = "0.0.0" ]; then
	exit 0
fi

# If the versions match, then we are ok
if [ "${firmware_ver}" = "${current_ver}" ]; then
	exit 0
fi

# Ok, have to flash the firmware then
echo "."
echo "Flashing ThunderStorm card to update firmware from ${current_ver} to ${firmware_ver}."
( cd /usr/local/tsc ; ./programAll )
echo "Rebooting."
shutdown -r now
sleep 3600
