#!/bin/bash

current_kernel=`uname -r`
base_dir="/opt/hp/graphics/ati"
build_dir="/lib/modules/fglrx"
mod_dir="/lib/modules/${current_kernel}/kernel/drivers/char/drm"

# Make sure user is root
if [[ `whoami` != "root" ]]
then
    echo ""
    echo "ERROR: You must be root to run this script."
    echo ""
    exit
fi

echo ""
echo "Configuring FireGL acclerated driver, please wait..."
echo ""

# Weak attempt to be sure kernel source is in place: 
if [ ! -f /lib/modules/${current_kernel}/build/include/linux/version.h ]; then
    echo "ERROR: kernel source tree not found.  Aborting..."
    echo ""
    exit
fi

# Clear out any old module if exists
if [ -f ${mod_dir}/fglrx.ko ]; then
   rm -f ${mod_dir}/fglrx.ko
fi

if [ -f ${mod_dir}/fglrx.o ]; then
   rm -f ${mod_dir}/fglrx.o
fi

# Clear out any objects in build area
rm -f ${build_dir}/*.o
rm -f ${build_dir}/*.ko
rm -f ${build_dir}/build_mod/2.6.x/*.o
rm -f ${build_dir}/build_mod/2.6.x/*.ko

# Now build fglrx module 
cd ${build_dir}/build_mod
sh make.sh > /dev/null 
cd ${build_dir}
sh make_install.sh > /dev/null

# Sanity check
ls ${mod_dir}/fglrx.*

# Weak check for success:
if ! grep -q "copying fglrx." /lib/modules/fglrx/build_mod/make.sh.log;
then
    echo "ERROR: Build of fglrx module failed."
    echo "See /lib/modules/fglrx/build_mod/make.sh.log"
    echo ""
    exit
fi

# Make sure 'atimodconfig' init script is active
/sbin/chkconfig --add atimodconfig > /dev/null

# Create link to documentation
cd ${base_dir}         
ln -s /usr/share/doc/fglrx ati-docs

# X configuration
# Run 'aticonfig' to generate initial X configuration
# Note: Dont confuse this with the HP atimodconfig init script
# If 'fglrx' device already configured, this will just exit.
/usr/X11R6/bin/aticonfig --initial 

modprobe fglrx

echo "- COMPLETE!"
echo "- NOTE: Your X configuration has been modified to use the"
echo "-       fglrx accelerated driver."

exit 0

