#!/bin/bash

set -x -e 

SLIC=/sys/firmware/acpi/tables/SLIC
XENPATH=$1

set -u

if [ ! -e ${XENPATH}/tools/firmware/hvmloader/acpi/acpi2_0.h ] ; then
	echo "Pass the path to the xen-4.5.0 directory as the first argument"
	exit 1
elif ! grep @@OEM_ID@@ ${XENPATH}/tools/firmware/hvmloader/acpi/acpi2_0.h ; then
	echo "You need to apply xen-4.5.0-slic.patch first:"
	echo "cd /path/to/xen-4.5.0; patch -Np1 -i /path/to/xen-4.5.0-slic.patch"
	exit 1
fi

if [ -r $SLIC ] ; then
	OEMID="`cat $SLIC | dd skip=10 count=6 bs=1 2> /dev/null`"
	TABLEID="`cat $SLIC | dd skip=16 count=8 bs=1 2> /dev/null`"
	REVNUM4="`cat $SLIC | dd skip=27 count=1 bs=1 2> /dev/null | xxd -p`"
	REVNUM3="`cat $SLIC | dd skip=26 count=1 bs=1 2> /dev/null | xxd -p`"
	REVNUM2="`cat $SLIC | dd skip=25 count=1 bs=1 2> /dev/null | xxd -p`"
	REVNUM1="`cat $SLIC | dd skip=24 count=1 bs=1 2> /dev/null | xxd -p`"
	REVNUM="0x$REVNUM4$REVNUM3$REVNUM2$REVNUM1"

	xxd -i $SLIC | grep -v len | sed 's/unsigned char.*/static char SLIC[] = {/' > ${XENPATH}/tools/firmware/hvmloader/acpi/slic.h

	sed -i -e "s/@@OEM_ID@@/${OEMID}/" -e "s/@@TABLE_ID@@/$TABLEID/" \
		-e "s/@@REV_NUM@@/${REVNUM}/" \
		${XENPATH}/tools/firmware/hvmloader/acpi/acpi2_0.h
else
	echo "No SLIC table in BIOS and/or not readable - sorry."
fi
