#! /bin/sh

PREREQ=""

prereqs()
{
	echo "$PREREQ"
}

case $1 in
prereqs)
	prereqs
	exit 0
	;;
esac

. /scripts/functions

[ "$quiet" != "y" ] && log_begin_msg "Initializing RAM disk"
  # We check for available memory anyways and limit the ramdisks
  # to a reasonable size.
  FOUNDMEM="$(awk '/MemTotal/{print $2}' /proc/meminfo)"
  TOTALMEM="$(awk 'BEGIN{m=0};/MemFree|Cached/{m+=$2};END{print m}' /proc/meminfo)"

  # Be verbose
  [ "$quiet" != "y" ] &&  _log_msg "Total memory found: ${FOUNDMEM} kB"

  # Now we need to use a little intuition for finding a ramdisk size
  # that keeps us from running out of space, but still doesn't crash the
  # machine due to lack of Ram
  
  # Minimum size of additional ram partitions
  MINSIZE=100000
  # At least this much memory minus 30% should remain when home and var are full.
  MINLEFT=16000
  # Maximum ramdisk size
  MAXSIZE="$(expr $TOTALMEM - $MINLEFT)"
  # Default ramdisk size for ramdisk
  RAMSIZE="$(expr $TOTALMEM / 5)"
  
  # Check for sufficient memory to mount extra ramdisk for /var
  if [ -n "$TOTALMEM" -a "$TOTALMEM" -gt "$MINLEFT" ]; then
    test -z "$RAMSIZE" && RAMSIZE=1000000
    # tmpfs/varsize version, can use swap
    RAMSIZE=$(expr $RAMSIZE \* 2)
    #echo -n "${CRE}${BLUE}Creating ${YELLOW}/ramdisk${BLUE} (dynamic size=${RAMSIZE}k) on ${MAGENTA}shared memory${BLUE}...${NORMAL}"
    [ "$quiet" != "y" ] &&  _log_msg "Creating RAM disk (size ${RAMSIZE} kb)"
    mkdir -p ${rootmnt}/ramdisk
    mount -t tmpfs -o "size=${RAMSIZE}k" ramdisk ${rootmnt}/ramdisk
    chmod 755 ${rootmnt}/ramdisk
    mkdir ${rootmnt}/ramdisk/tmp
    mkdir ${rootmnt}/ramdisk/root
    mkdir ${rootmnt}/ramdisk/home
    mkdir ${rootmnt}/ramdisk/media
    chmod 1777 ${rootmnt}/ramdisk/tmp
    chmod 700 ${rootmnt}/ramdisk/root
    if [ -d ${rootmnt}/root/.ssh ]; then
      cp -rp ${rootmnt}/root/.ssh ${rootmnt}/ramdisk/root/
    fi
    chmod 755 ${rootmnt}/ramdisk/home
    chmod 755 ${rootmnt}/ramdisk/media
    mount -o bind ${rootmnt}/ramdisk/tmp ${rootmnt}/tmp
    mount -o bind ${rootmnt}/ramdisk/root ${rootmnt}/root
    mount -o bind ${rootmnt}/ramdisk/home ${rootmnt}/home
    mount -o bind ${rootmnt}/ramdisk/home ${rootmnt}/media
    #echo "${BLUE}Done.${NORMAL}"
  fi

[ "$quiet" != "y" ] && log_end_msg

