#!/bin/sh
#
# readahead	Prereads programs required for startup into memory
#
# Authors:	Karel Zak <kzak@redhat.com>
#
# chkconfig: 5 96 99
# description:  This service causes the programs used during startup \
#		to be loaded into memory before they are needed,\
#		thus improving startup performance
#
# Copyright (C) 2005,2006,2007  Red Hat, Inc.
#
### BEGIN INIT INFO
# Provides: readahead_later
# Default-Start: 5
# Default-Stop: 0 1 6
# Required-Start: $local_fs
# Required-Stop: $local_fs
# Short-Description: start and stop later readahead
# Description: Start and stop later readahead
### END INIT INFO

# Sanity checks.
[ -x /usr/sbin/readahead ] || exit 0

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

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

RETVAL=0
VAR_SUBSYS_READAHEAD="/var/lock/subsys/readahead_later"
READAHEAD_CMD="/usr/sbin/readahead"

start() {
    LTYPE="later"
    READAHEAD_BASE="/var/lib/readahead"

    [ -d "$READAHEAD_BASE" ] || return 6

    echo -n "Starting background readahead ($LTYPE, "

    if [ -s "$READAHEAD_BASE/$LTYPE.sorted" ]; then
	echo -n "fast mode): "
	$READAHEAD_CMD --dont-sort $READAHEAD_BASE/$LTYPE.sorted >/dev/null &
    elif [ -s "$READAHEAD_BASE/custom.$LTYPE" ]; then
	echo -n "customized): "
	$READAHEAD_CMD $READAHEAD_BASE/custom.$LTYPE >/dev/null &
    else
	echo -n "full mode): "
	$READAHEAD_CMD $READAHEAD_BASE/*.$LTYPE >/dev/null &
    fi

    ret=$?
    if [ $ret -eq 0 ]; then
       success; echo
    else
       failure; echo; return 1
    fi

    touch $VAR_SUBSYS_READAHEAD
    return $ret
}


stop() {
   rm -f $VAR_SUBSYS_READAHEAD
   return $?
}

status() {
   [ -r $VAR_SUBSYS_READAHEAD ] || exit 2
}

# See how we were called.
case "$1" in
    start)
	start
	RETVAL=$?
	;;
    stop)
	stop
	RETVAL=$?
	;;
    status)
	status $READAHEAD_CMD
	RETVAL=$?
        ;;
    restart)
	stop
	start
	RETVAL=$?
	;;
    reload)
	start
	RETVAL=$?
        ;;
    *)
	echo "Usage: $0 {start|stop|status|restart|reload}"
	RETVAL=3
	;;
esac
exit $RETVAL
