#!/bin/bash
#
#	/etc/rc.d/init.d/afs-build-kmod
# 
# AFS currently starts at 50, this should be as close to it as possible
# 
# chkconfig: - 49 49
# description: Checks for and builds AFS kernel module if necessary
#
# Source function library.
. /etc/init.d/functions

RETVAL=0

#
#	See how we were called.
#

rhgbflag=/var/tmp/afs-build-kmod-rhgb-flag.$$

source /opt/mit-openafs-setup/lib/functions.sh

rhgb_keepalive() {
    # RHGB will bail to VT1 if there's no activity for 30 secs
    # This will help it deal when building the module
    if [ -w /etc/rhgb/temp/rhgb-console ]; then
	i=1
	sp="/-|-\|"
	echo -ne "\033[7m " > /etc/rhgb/temp/rhgb-console
	while true; do
	    sleep 0.1
	    echo -ne "\b${sp:i++%${#sp}:1}" > /etc/rhgb/temp/rhgb-console
	    [ ! -f $rhgbflag ] && break
	done
	echo -e "\033[1m" > /etc/rhgb/temp/rhgb-console
    fi
}

start() {
    echo -n "Checking for suitable OpenAFS kernel module: "
    # -A will only rebuild if necessary
    /sbin/depmod -A
    /sbin/modprobe -nq openafs 2>/dev/null
    if [ $? != 0 ]; then
	[ -x /usr/bin/rhgb-client ] && /usr/bin/rhgb-client --details=yes
	output "not found"
	output -n "Attempting to fetch binary module:"
	/opt/mit-openafs-setup/bin/setup -k
	RV=$?
	[ $RV != 0 ] && output "failed"
	if [ $RV = 0 ]; then
	    output "success"
	    /sbin/depmod -A
	    /sbin/modprobe -nq openafs 2>/dev/null
	    if [ $? = 0 ]; then
		output "Module successfully installed."
		echo_success
		sleep 1
		return $RETVAL
	    else
		output "Binary module failed to install correctly."
	    fi
	fi
	output "Attempting to build module: (this can take more than 5 minutes)"
	touch $rhgbflag
	rhgb_keepalive &
	/opt/mit-openafs-setup/bin/build-module -n
	
	if [ $? != 0 ]; then
	    rm -f $rhgbflag
	    output "Failed to build module.  OpenAFS will not be available."
	    RETVAL=255
	    echo_failure
	else
	    rm -f $rhgbflag
	    echo_passed
	fi
	# Give time to read messages
	sleep 1
    else
	echo_success
    fi
    echo
    return $RETVAL
}

stop() {
    echo_success
    echo
    return $RETVAL
}


restart() {
	stop
	start
}	

reload() {
	restart
}	

status_afs_build_kmod() {
    echo "afs-build-kmod is ok"
    return 0
}

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

exit $?
exit $RETVAL
