#!/bin/bash
LDD="1"
STRACE="1"
if ! strace echo &>/dev/null; then
  echo "WARN: No strace found!, using the ldd way (not as good)"
  echo "If you install strace readahead will be more accurate"
  sleep 2
  STRACE=""
fi

if [ -z "$DESTDIR" ]; then
    DESTDIR="/"
fi

mkdir -p "${DESTDIR}etc/initng/readahead.d"
MAKEREADAHEAD=$(echo `dirname $0`/makereadahead)

#Files we can just "run" directly, no need to include commands
MISCFILES="
/bin/bash -c exit
/bin/cat < /dev/null
/bin/chmod
/bin/chown
/bin/dd --help
/bin/grep
/bin/hostname
/bin/mount
/bin/rm
/bin/sed
/bin/sleep
/bin/touch
/bin/true
/bin/false
/bin/uname
/sbin/modprobe --help
/sbin/fsck --help
/sbin/fsck.ext3 --help

/bin/cut
/bin/env
/bin/awk
/bin/gawk
/usr/bin/cut
/usr/bin/env
/usr/bin/awk
/usr/bin/gawk
"

if grep -q 'daemon/gdm' "${DESTDIR}/etc/initng/default.runlevel"; then
    MISCFILES=$(echo -e "${MISCFILES}\n/usr/bin/gdm --usage")
fi

READAHEAD=""
ADDED_FILES=""

IFS=$'\n'
for x in $MISCFILES; do
	FILE=$(echo "$x" | cut -d ' ' -f 1 | grep '.')
	if [ -e "$FILE" ]; then
                ADDED_FILES="$ADDED_FILES $FILE"
		if [ ! -z "$STRACE" ]; then
		    #Custom files, files we need commands
		    TMP=$(sh $MAKEREADAHEAD $x)
		    READAHEAD=$(echo -e "$TMP\n$READAHEAD")
	        fi
		if [ ! -z "LDD" ]; then
	            TMP=$(ldd $FILE | cut -s -d \> -f 2 | cut -s -d \( -f 1 | cut -c 2-)
	            READAHEAD=$(echo -e "$TMP\n$READAHEAD")
		fi
	else
		echo "Skipping $FILE"
	fi
done
echo "Files added to cache :"
echo "$ADDED_FILES"
echo "Writing readahead basefile to ${DESTDIR}etc/initng/readahead.d/base"
echo "$READAHEAD" | sort -u -b | grep '.' > "${DESTDIR}etc/initng/readahead.d/base"

if [ -f /etc/readahead/readahead.new ]; then
    ln -s /etc/readahead/readahead.new "${DESTDIR}etc/initng/readahead.d/system" &>/dev/null
elif [ -f /etc/readahead/readahead ]; then
    ln -s /etc/readahead/readahead "${DESTDIR}etc/initng/readahead.d/system" &>/dev/null
elif [ -f /etc/readahead ]; then
    ln -s /etc/readahead "${DESTDIR}etc/initng/readahead.d/system" &>/dev/null
fi

exit 0
