#!/bin/bash
#
#	/etc/rc.d/init.d/preload
#
# Starts the preload daemon
#
# chkconfig: 5 099 1
# description: Adaptive readahead daemon
# processname: preload
#
### BEGIN INIT INFO
# Provides:          preload.sourceforge.net
# Required-Start:    $local_fs $remote_fs $time
# Required-Stop:     $local_fs $remote_fs $time
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: Adaptive readahead daemon
# Description:       Analyzes what applications users run and tries to predict
#                    what they would like to run and loads them into memory
#                    beforehand.
### END INIT INFO


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

[ -x /usr/sbin/preload ] || exit 0

if [ -f /etc/sysconfig/preload ]; then
	. /etc/sysconfig/preload
fi

# Check for > MIN_MEMORY MB
MIN_MEMORY=${MIN_MEMORY:-256}
free -m | awk '/Mem:/ {exit ($2 >= ('"$MIN_MEMORY"'))?0:1}' || exit 0

# Check for ionice and use idle scheduling if available
RUNAS=""
IONICE="/usr/bin/ionice"
if [ -n "$IONICE_OPTS" ]; then
	if [ -x "$IONICE" ]; then
		RUNAS="$IONICE $IONICE_OPTS"
	else
		echo "ionice not found, running with normal io priority" >&2
	fi
fi

RETVAL=0

#
# See how we were called.
#

start() {
	# Check if it is already running
	if [ ! -f /var/lock/subsys/preload ]; then
	    echo -n $"Starting preload daemon: "
	    daemon $RUNAS /usr/sbin/preload $PRELOAD_OPTS
	    RETVAL=$?
	    [ $RETVAL -eq 0 ] && touch /var/lock/subsys/preload
	    echo
	fi
	return $RETVAL
}

stop() {
	echo -n $"Stopping preload daemon: "
	killproc /usr/sbin/preload
	RETVAL=$?
	[ $RETVAL -eq 0 ] && rm -f /var/lock/subsys/preload
	echo
        return $RETVAL
}


restart() {
	stop
	start
}	

reload() {
	trap "" SIGHUP
	killall -HUP preload
}	

case "$1" in
start)
	start
	;;
stop)
	stop
	;;
reload)
	reload
	;;
restart)
	restart
	;;
condrestart)
	if [ -f /var/lock/subsys/preload ]; then
	    restart
	fi
	;;
status)
	status preload
	;;
*)
	echo $"Usage: $0 {start|stop|status|restart|condrestart|reload}"
	exit 1
esac

exit $RETVAL
