#!/bin/sh

#
# $VER: card_detect.sh 0.4 (11.12.2002) daveSSH
#


PATH_DEST=/etc/X11
PATH_ORIG=/scripts/cardDetect
FILE_1=${PATH_ORIG}/pcitable.gz
FILE_2=${PATH_ORIG}/Cards

XF86_CFG_ORIG=${PATH_ORIG}/XF86Config.orig
XF86_CFG_VMWARE=${PATH_ORIG}/XF86Config.vmware
XF86_CFG=${PATH_DEST}/XF86Config
DRIVER_MAP_FILE=${PATH_ORIG}/freesbiePCItable.map.gz

if [ -f ${XF86_CFG} ]; then
	echo "XF86Config found... skipping"
  exit
fi

IS_VMWARE=`pciconf -lv | grep -i vmware`
if [ "$IS_VMWARE" != "" ]; then
	cp ${XF86_CFG_VMWARE} ${XF86_CFG}
    exit
fi

PCICONF=`pciconf -lv | grep -B 4 VGA | awk '/chip=/ { split($4, a, "="); print a[2]; }'`
CHIP_ID=`echo ${PCICONF} | awk '{ print(substr($0,1,6)); }'`
VENDOR_ID=`echo ${PCICONF} | awk '{ print(substr($0,7,10)); }'`
STR_ID=`printf "0x%s\t%s" $VENDOR_ID $CHIP_ID`
LONG_STR_ID=`zgrep "$STR_ID" ${FILE_1}`
CARD=`echo $LONG_STR_ID | cut -d: -f 2 | cut -d\" -f 1`
IO=`awk -v scheda="NAME $CARD" '{ 
    if ($0 == scheda) {
        while ($0 != " " && $0 != "\n" && $0 != "") {
            getline;
            if ($1 == "DRIVER")
                print $2;
            else if ($1 == "SEE")
                print "other@" substr($0,5,length($0)-4);
        }
        exit
    }
}' $FILE_2`
DRIVER_STR=`echo $IO | cut -d@ -f 1`
if [ "$DRIVER_STR" = "other" ]; then
    OTHER=`echo $IO | cut -d@ -f 2`
    CARD=`echo "$OTHER"`
    DRIVER_STR=`awk -v scheda="NAME $CARD" '{ 
    if ($0 == scheda) {
        while ($0 != " " && $0 != "\n" && $0 != "") {
            getline;
            if ($1 == "DRIVER")
                print $2;
            else if ($1 == "SEE")
                print "other@" substr($0,5,length($0)-4);
            }
            exit
        }
    }' $FILE_2`
else
    DRIVER_STR=`echo $IO`
fi
echo "$CARD detected, using $DRIVER_STR driver"

case "${DRIVER_STR:-NULL}" in
NULL)
	echo "No drivers found... using vesa"
	cp ${XF86_CFG_ORIG} ${XF86_CFG}
	;;
vesa)
	cp ${XF86_CFG_ORIG} ${XF86_CFG}
	;;
*)
	sed "s/vesa/${DRIVER_STR}/" < ${XF86_CFG_ORIG} > ${XF86_CFG}
	;;
esac
