#!/bin/bash
function checkdate()
{
	y=$1
	m=$2
	d=$3

	fixed="platform (`uname -v`) post-dates fix"
	year=`uname -v | cut -c 8-11`

	if [[ $year -lt 2010 ]]; then
		echo $fixed
		exit 0
	fi

	if [[ $year -gt 2020 ]]; then
		echo $fixed
		exit 0
	fi

	if [[ $year -gt $y ]]; then
		echo $fixed
		exit 0
	fi

	if [[ $year -eq $y ]]; then
		month=`uname -v | cut -c 12-13`

		if [[ $month -gt $m ]]; then
			echo $fixed
			exit 0
		fi

		if [[ $month -eq $m ]]; then
			day=`uname -v | cut -c 14-15`

			if [[ $day -gt $d ]]; then
				echo $fixed
				exit 0
			fi
		fi
	fi
}

checkdate 2015 11 11

variant1=/tmp/OS-4930-check.variant1
variant2=/tmp/OS-4930-check.variant2
out=/tmp/OS-4930-check.out

cat > $variant1 <<EOF
lx_userregs_to_regs:            pushq  %rbp
lx_userregs_to_regs+1:          movq   %rsp,%rbp
EOF

cat > $variant2 <<EOF
lx_user_regs_copyin:            pushq  %rbp
lx_user_regs_copyin+1:          movq   %rsp,%rbp
EOF

echo "lx_userregs_to_regs::dis" | mdb -k 2> /dev/null | head -2 > $out
if cmp $out $variant1 > /dev/null 2> /dev/null ; then
	echo "found variant 1; hot-patching lx_userregs_to_regs prolog"
	echo "lx_userregs_to_regs/Z 9090c300000005b8" | mdb -kw
	exit 0
fi

echo "lx_user_regs_copyin::dis" | mdb -k 2> /dev/null | head -2 > $out
if cmp $out $variant2 > /dev/null 2> /dev/null; then
	echo "found variant 2; hot-patching lx_user_regs_copyin prolog"
	echo "lx_user_regs_copyin/Z 9090c300000005b8" | mdb -kw
	exit 0
fi

cat > $variant1 <<EOF
lx_userregs_to_regs:            movl   \$0x5,%eax
lx_userregs_to_regs+5:          ret    
EOF

cat > $variant2 <<EOF
lx_user_regs_copyin:            movl   \$0x5,%eax
lx_user_regs_copyin+5:          ret    
EOF

echo "lx_userregs_to_regs::dis" | mdb -k 2> /dev/null | head -2 > $out
if cmp $out $variant1 > /dev/null 2> /dev/null; then
        echo "found variant 1, but lx_userregs_to_regs is already patched"
        exit 0
fi

echo "lx_user_regs_copyin::dis" | mdb -k 2> /dev/null | head -2 > $out
if cmp $out $variant2 > /dev/null 2> /dev/null; then
        echo "found variant 2, but lx_user_regs_copyin is already patched"
        exit 0
fi

echo "did not find either variant"
