#!/bin/sh
#
# ati-fglrx:	Enable/Disable ati-fglrx driver in XF86Config
#
# chkconfig:    2345 98 02
# description:  This script will check if the ati-fglrx kernel module is present \
# 	for the running kernel and will warn if is missing. \
#	Also during stop it will try to enable or disable the driver if \
#	it was requested before by ati-fglrx-config-display
# processname: 	ati-fglrx

# Source function library.
. /etc/rc.d/init.d/functions

exec="/usr/sbin/ati-fglrx-config-display"
prog="$(basename ${exec})"
lockfile=/var/lock/subsys/ati-fglrx

test -e /etc/sysconfig/$prog && . /etc/sysconfig/$prog
module="/lib/modules/$(uname -r)/kernel/drivers/char/drm/fglrx.ko" 

start() {
    if [[ "${FGLRXSTATUS}" = "enabled" ]]
    then
        if action "Checking for ati-fglrx kernel module" test -f $module
	    then
            retval=0
        else
	    echo
	    echo "`basename $module` module for `uname -r` kernel not found"
	    echo "DRI will not work within X with the ati-fglrx driver. Get"
	    echo "an updated/suitable 'kernel-module-fglrx-<kernelver>' rpm"
	    echo "from rpm.livna.org"
            retval=1
            sleep 3 
        fi
    fi
    touch "$lockfile"
    return $retval
}

stop() {
    if [[ "${FGLRXSTATUS}" = "enabled" ]]
    then
	# Do nothing
        retval=0
    elif [[ "${FGLRXSTATUS}" = "dritobeenabled" ]]
    then
    	action "Enabling dri for X-driver" /usr/sbin/ati-fglrx-config-display enabledri &>/dev/null
        retval=$?
    fi 
    [[ -f "$lockfile" ]] && rm -f "$lockfile"
    return $retval
}

restart() {
    stop
    start
}	

status() {
    if [[ -e "${lockfile}" ]]
    then
	echo "Init-Script is running."
    else
	echo "Init-Script is not running."
    fi

    if [[ "${FGLRXSTATUS}" = "enabled" ]]
    then
	echo "fglrx driver is enabled."
	if /sbin/lsmod | grep "radeon" &>/dev/null
	then
		echo "DRI will work after restarting System or removing the kernel-module 'radeon'"
	fi
    elif [[ "${FGLRXSTATUS}" = "disabled" ]]
    then
	echo "fglrx driver is disabled."
    elif [[ "${FGLRXSTATUS}" = "dritobeenabled" ]]
    then
	echo "fglrx-driver disabled, DRI will be enabled after system restart."
    fi 
}


case "$1" in
    start|stop|restart|status)
        $1
        ;;
    *)
        echo $"Usage: $0 {start|stop|restart|status}"
        exit 1
esac
