#!/bin/sh

#
# Generates sorted readahead files
#
# Copyright (C) 2009, 2011 by Raphael Geissert
# Copyright (C) 2007  Red Hat, Inc.
# Karel Zak <kzak@redhat.com>
#

TYPES="early later"
READAHEAD_CMD="/sbin/readahead"
READAHEAD_BASE="/etc/readahead.d"
MERGE_LISTS=false

[ -x "$READAHEAD_CMD" ] || exit 0

if [ -z "$RENICED" ]; then
    export RENICED=yes
    exec /sbin/start-stop-daemon --start -N +19 -I idle \
	    --exec $READAHEAD_CMD --startas $0
fi

if [ -f /run/readahead ]; then
    . /run/readahead
    if $MOUNTED_USR && $MOUNTED_VAR; then
	MERGE_LISTS=true
    fi
fi

get_lists() {
    local type="$1" allow_null="${2:-true}"

    if [ -s "$READAHEAD_BASE/custom.$type" ]; then
	echo "$READAHEAD_BASE/custom.$type"
    else
	local f found=false
	for f in "$(ls $READAHEAD_BASE/*.$type 2>/dev/null)"; do
	    if [ -f "$f" ]; then
		echo "$f"
		found=true
	    fi
	done
	if ! $found && $allow_null; then
	    # otherwise readahead(8) would abort
	    echo /dev/null
	fi
    fi
}

if $MERGE_LISTS; then
    extra_opts=--sort

    major=$(stat -c '%D' . | cut -b1)
    if [ -f "/sys/dev/block/${major}:0/queue/rotational" ]; then
	rotational="$(cat "/sys/dev/block/${major}:0/queue/rotational")"
	if [ "$rotational" = "0" ]; then
	    extra_opts=--build
	fi
    fi

    lists=
    for type in $TYPES; do
	typel="$(get_lists $type false)"

	# We don't want lists=" /etc/..." because of the -n test below
	# We need lists='' instead of lists='  ' when no list is found
	if [ -n "$lists" ]; then
	    lists="$typel"
	else
	    lists="$lists $typel"
	fi
    done

    if [ -n "$lists" ]; then
	$READAHEAD_CMD $extra_opts --output="$READAHEAD_BASE/early.sorted" $lists >/dev/null 2>&1
	# only write to later.sorted if needed
	if [ ! -f "$READAHEAD_BASE/later.sorted" ] || [ -s "$READAHEAD_BASE/later.sorted" ]; then
	    : > "$READAHEAD_BASE/later.sorted"
	fi
    else
	: > "$READAHEAD_BASE/early.sorted"
	: > "$READAHEAD_BASE/later.sorted"
    fi
else
    for LTYPE in $TYPES; do
	FLS="$(get_lists $LTYPE)"

	if [ -n "$FLS" ]; then
	    $READAHEAD_CMD --sort --output=$READAHEAD_BASE/$LTYPE.sorted $FLS >/dev/null 2>&1
	fi
    done
fi
