#!/bin/bash -e

XORG_CONF=/etc/X11/xorg.conf
XORG_CONF_BCKP=/etc/X11/.xorg.conf.parallels-backup

DEVS=/sys/bus/pci/devices

# Prints bus-id of primary VGA adapter in format XX:XX.X
get_primary_vga()
{
	IFS=$'\n'
	for d in `ls -1 "$DEVS"`; do
		# searching for PCI bridges
		dev_class=`<"$DEVS"/$d/class`
		[ $dev_class != 0x060400 ] && continue

		# searching for all PCI devices connected to current bridge
		subdevs=`ls -1 $DEVS/$d/ |
			grep -E '^[[:xdigit:]]{4}:[[:xdigit:]]{2}:[[:xdigit:]]{2}.[[:xdigit:]]$'`
		for sd in $subdevs; do
			# searching for all VGA adapters
			subdev_class=`<"$DEVS/$d/$sd/class"`
			[ $subdev_class != 0x030000 ] && continue

			# Ok, now we've found VGA adapter $sd connected to bridge $d
			# Read byte with offset 0x3e from PCI bridge config...
			pci_reg=`dd bs=1 count=1 skip=62 if="$DEVS/$d/config" status=noxfer 2>/dev/null |
				od -x | awk '{print $2}' | sed '2d'`
			# ... and check that 0x8 bit is set in that bit
			# If this bit is set - primary VGA adapter is found
			if (("0x$pci_reg" & 0x8)); then
				# here sd has value XXXX:XX:XX.X
				echo $sd | sed 's/^[0-9a-f]\{4\}://'
				return 0
			fi
		done
	done

	# Primary adapter is not connected to PCI pridge, so it is just on bus 0.
	PATH=$PATH:/sbin
	for i in `lspci -n`; do
		echo "$i" | grep -qE '^00:[[:xdigit:]]{2}.[[:xdigit:]] 0300'
		if [ $? -eq 0 ]; then
			echo "$i" | cut -d' ' -f1
			return 0
		fi
	done
	unset IFS

	return 1
}

video_cards_to_isolate()
{
	VTDHOOK_CONF=/etc/parallels/vtd.hook
	primary_vga=`get_primary_vga`
	[ $? -ne 0 ] && return 1
	echo "$primary_vga" |
		sed -r 'y/:/./; s/0([0-9a-f])/\1/g; y/abcdf/ABCDF/' |
			while read video_card; do
				if ! grep -qs $video_card "$VTDHOOK_CONF" 2> /dev/null; then
					# This video card is not assigned to VM
					# So isolate it!
					video_card_dec=
					OLDIFS="$IFS"
					IFS='.' 
					for i in $video_card; do
						video_card_dec="${video_card_dec}${video_card_dec:+:}`echo "ibase=16; $i" | bc`"
					done
					echo "$video_card_dec"
					IFS="$OLDIFS"
				fi
			done
}


patch_xconf ()
{

	video_cards_to_isolate=`video_cards_to_isolate`
	test -z "$video_cards_to_isolate" && return 0

	cp -f "$XORG_CONF" "$XORG_CONF_BCKP"

	awk -v cards_list="$video_cards_to_isolate" '
			BEGIN {
				in_server_layout = 0
				split(cards_list, cards_array)
			}

			{
				if ($0 ~ /^[\t ]*Section[\t ]+"ServerLayout"/)
					in_server_layout = 1

				if (in_server_layout == 1 && ($0 ~ /^[\t ]*EndSection\[\t ]+/ || $0 ~ "EndSection$"))
				{
					in_server_layout = 0
					for (i in cards_array)
						print sprintf("\tOption\t\"IsolateDevice\"\t\"PCI:%s\"", cards_array[i])
					print $0
				}
				else
				if ($0 !~ /^[\t ]*Option[\t ]+"IsolateDevice"/)
					print $0
			}
		' "$XORG_CONF_BCKP" > "$XORG_CONF"
}


# Removes all "IsolateDevice" options
unpatch_xconf()
{
	cp -f "$XORG_CONF" "$XORG_CONF_BCKP"

	awk '
			{
				if ($0 !~ /^[\t ]*Option[\t ]+"IsolateDevice"/)
					print $0
			}
		' "$XORG_CONF_BCKP" > "$XORG_CONF"
}

retcode=0

test -f $XORG_CONF || exit 0

if [ "x$1" = "x-r" ]; then
	unpatch_xconf
	retcode=$?
else
	patch_xconf
	retcode=$?
fi

exit $retcode

