#!/bin/sh
# a script to update Driver "..." in xorg.conf as seen on PCI
# by Michael Shigorin <mike@osdn.org.ua>, 2005, 2006
# use and modify freely

# thanks for tips to Sergey Vlasov <vsu@altlinux>
# and Sergey Bolshakov <sbolshakov@altlinux>

# init: avoid vesa but still have it as a fallback
VESA="Generic VESA compatible"
CARD=
DRIVER="vesa"

debug() {
	[ -n "$DEBUG" ] && echo $0: $* >&2
}

error() {
	echo $0: $* >&2; exit 1
}

( which x11createconfig && which x11setupdrv && \
  which x11setupdrv ) >&/dev/null || {
	error "needed utilities missing"
}

# put it to function since |while will go subshell
# and won't influence main process' vars
cards() {
		x11createconfig -c \
		| grep -v "$VESA" \
		| awk -F: '/^card:/ { print $2; }' \
		| while read type; do
			debug "considering non-vesa [$type]"
			[ -n "$type" ] && {
				[ -n "$CARD" ] && { 
				echo "$0: warning, overriding already acquired $CARD!" >&2
			}
			CARD="$type"
			echo "$CARD"
		} || echo "$0: hmm, empty card type in x11createconfig output?" >&2
	done
}

# x11setupdrv -s doesn't support multihead yet
# (actually all of this is a relatively quick hack
# to plug a hole with automatic more-or-less setup
# right at bootup...) -- taking presumably primary
# device available on higher numbered PCI bus
CARD=`cards | tail -1`
debug "card: [$CARD]"

chip=`vcardinfo "$CARD" | awk '/^xdriver\t/ { print $2; exit; }'` || {
	error "pciscan failed"
}

[ -n "$chip" ] && DRIVER="$chip"
debug "driver: [$DRIVER]"

CURRENT=`x11setupdrv -d --nosetup | sed 's/driver name: //'` || {
	error "x11setupdrv failed"
}

debug "current: [$CURRENT]"

[ "$DRIVER" == "$CURRENT" ] && {
	debug "nothing to modify, driver is the same"
	exit 0	# nothing to be done
}

debug ">> setting driver to [$DRIVER]"

x11setupdrv -s "$DRIVER" || {
	error "x11setupdrv failed to modify configuration"
}
