#!/bin/sh -ex

PREREQ=""
prereqs()
{
	echo "$PREREQ"
}
case $1 in
# get pre-requisites
prereqs)
	prereqs
	exit 0
	;;
esac

USBRAM_FILE=${USBRAM_FILE:-root.squashfs}
USBRAM=${USBRAM:-no}

rootmnt=${rootmnt:-/}

for x in $(cat /proc/cmdline); do
	case ${x} in
	usbram_file=*)
		USBRAM_FILE=${x#*=}
		;;
	usbram=*)
		USBRAM=${x#*=}
		;;
	esac
done

case "${USBRAM}" in
	yes|enable)
		;;
	*)
		log_warning_msg "USB RAM disk loading is disabled"
		exit 0
		;;
esac

if grep -q '^brd ' /proc/modules; then
	log_warning_msg "brd module already loaded"
	exit 0
fi

USBRAM_DIR=${rootmnt}

if [ ! -f "${USBRAM_DIR}/${USBRAM_FILE}" ]; then
	log_warning_msg "File ${USBRAM_FILE} on ${USBRAM_DEVICE} not found"
	exit 0
fi

USBRAM_SIZE=`ls -s ${USBRAM_DIR}/${USBRAM_FILE} | cut -d' ' -f1`
USBRAM_SIZE=$((8 * (${USBRAM_SIZE}/ (8*1024) + 1)))

modprobe brd rd_nr=1 rd_size=$((${USBRAM_SIZE} * 1024))
sleep 1

dd if="${USBRAM_DIR}/${USBRAM_FILE}" of=/dev/ram0

echo done > /dev/.usbram
