#!/bin/sh

# This script will download and update the Intel microcode


MICROCODE_REMOTE_DIR="http://people.debian.org/~cate/files/microcode"
MICROCODE_DIR=/usr/share/misc

MICROCODE_REMOTE_TINY=microcode.dat
MICROCODE_REMOTE_FULL=intel-microcode.dat

MICROCODE_TINY=intel-microcode.tiny.dat
MICROCODE_FULL=intel-microcode.dat

# Check the kernel version and return:
#  0 : for new kernel
#  1 : for buggy kernel that don't allow tiny microcodes

check_kernel () {
  uname -r | grep -Esqe \
"(2\.6\.16\.[5-9][0-9])|"\
"(2\.6\.16\.[1-9][0-9][0-9])|"\
"(2\.6\.18\.[5-9])|"\
"(2\.6\.19-rc[1-9])|"\
"(2\.6\.19$)|"\
"(2\.6\.19\.[1-9])|"\
"(2\.6\.[2-9][0-9])|"\
"(2\.6\.[1-9][0-9][0-9])" \
-
}


# Check wget
if ! which wget > /dev/null 2> /dev/null; then
    echo "wget not found. Please install wget" 1>&2
    exit 1
fi

# Check kernel
if check_kernel ; then
    # full version
    REMOTE="$MICROCODE_REMOTE_DIR/$MICROCODE_REMOTE_FULL"
    LOCAL="$MICROCODE_DIR/$MICROCODE_FULL"
else
    # tiny version
    REMOTE="$MICROCODE_REMOTE_DIR/$MICROCODE_REMOTE_TINY"
    LOCAL="$MICROCODE_DIR/$MICROCODE_TINY"
fi


if [ -f "$LOCAL" ] ; then
    DATE=$(sed -ne 's#^/\*\(.*\)\*/.*$#\1#p' "$LOCAL" | head -n 1 | date "+%Y%m%d" -f - )
    REMOTE_DATE=$(wget -t 2 -T 20 -q -O - "$MICROCODE_REMOTE_DIR/LATEST" )
    if [ "x$?" = "x0" ] ; then
	if [ "$REMOTE_DATE" -le "0$DATE" ] ; then
	    echo "No need to download a new microcode" 1>&2
	    exit 0
	fi
    else
	echo "Could not check the microcode version on server" 1>&2
	exit 1
    fi
fi

echo "Downloading a new version of microcode." 1>&2

if [ -x /bin/bzip2 ]; then
    if wget -t 2 -T 20 -q -O - "$REMOTE".bz2 | bzip2 -cd > "$LOCAL" ; then
	echo "microcode downloaded sucessfully" 1>&2
    else
        echo "Error on downloading the microcode." 1>&2
        echo "Install microcode manually. (See /usr/share/doc/microcode.ctl/README.Debian)" 1>&2
	exit 1
    fi
elif [ -x /bin/gzip ]; then
    if wget -t 2 -T 20 -q -O - "$REMOTE".gz | gzip -cd > $LOCAL ; then
        echo "microcode downloaded sucessfully" 1>&2
    else
        echo "Error on downloading the microcode." 1>&2
        echo "Install microcode manually. (See /usr/share/doc/microcode.ctl/README.Debian)" 1>&2
	exit 1
    fi
else
    if wget -t 2 -T 20 -q -O - "$REMOTE" | cat - > $LOCAL ; then
        echo "microcode downloaded sucessfully" 1>&2
    else
        echo "Error on downloading the microcode." 1>&2
        echo "Install microcode manually. (See /usr/share/doc/microcode.ctl/README.Debian)" 1>&2
	exit 1
    fi
fi

# load the new microcode


if [ "-$1" != "--no-reload" ] ; then
    /etc/init.d/microcode.ctl reload
fi

