#!/bin/sh
set -e
### BEGIN INIT INFO
# Provides:          stop-readahead-fedora
# Required-Start:    $all
# Required-Stop:     $remote_fs
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: init script for stopping readahead profiling
### END INIT INFO

READAHEAD_COLLECT_CMD="/sbin/readahead-collector"

[ -x $READAHEAD_COLLECT_CMD ] || exit 0

running=false
if test -f /.readahead_collect || grep -qw "profile" /proc/cmdline; then
    if pidof readahead-collector >/dev/null; then
	running=true
    fi
fi

# U: unknown
RUNLEVEL="${RUNLEVEL:-U}"

if [ "$RUNLEVEL" != 6 ] && [ "$RUNLEVEL" != 0 ]; then
    $running || exit 0
fi

[ ! -f /etc/default/readahead-fedora ] || . /etc/default/readahead-fedora

if [ "$SORT_AT_SHUTDOWN" = no ]; then
    SORT_AT_SHUTDOWN=false
    $running || exit 0
else
    SORT_AT_SHUTDOWN=true
fi

case "$1" in
    start|stop)
	if $running; then
	    (
	    rm -f /.readahead_collect
	    sleep ${READAHEAD_EXTRA_COLLECT:-0}
	    /sbin/start-stop-daemon --stop --quiet --oknodo \
		--exec "$READAHEAD_COLLECT_CMD"

	    if ! $SORT_AT_SHUTDOWN; then
		# wait until the collector exits before sorting the lists
		while pidof readahead-collector >/dev/null; do
		    sleep 3
		done
		exec /usr/share/readahead-fedora/build-lists
	    fi
	    ) &
	fi
	if $SORT_AT_SHUTDOWN && [ "$RUNLEVEL" = 6 -o "$RUNLEVEL" = 0 ]; then
	    . /lib/lsb/init-functions
	    log_begin_msg "Sorting readahead lists..."
	    if RENICED=yes /usr/share/readahead-fedora/build-lists; then
		log_end_msg 0
	    else
		log_end_msg $?
	    fi
	fi
    ;;
    restart|force-reload)
    ;;
    *)
	echo "Usage: /etc/init.d/stop-readahead {start|stop|restart|force-reload}"
	exit 1
    ;;
esac
