#! /bin/bash

#*********************************************************************
#
# mkramdisk -- mount a ramdisk on top of a directory
#
# This script is part of FAI (Fully Automatic Installation)
# (c) 2003-2010 by Thomas Lange, lange@informatik.uni-koeln.de
# Universitaet zu Koeln
#
#*********************************************************************

# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
mount_ramdisk() {

    # save all dirs and files under directory $1
    # mount tmpfs on top of dir $1
    # extract dirs and files into tmpfs

    local n=

    if [ ! -d "$1" ]; then
	echo "WARNING: $1 is not a directory. Cannot make it writeable."
	return
    fi

    echo

    set -e
    local tmp1=$(mktemp) || exit 12
    tar -C $1 -cf $tmp1 .
    mount $2 $3 -t tmpfs tmpfs $1 || exit 13
    echo "Ramdisk mounted onto $1"
    tar -C $1 -xf $tmp1
    rm -f $tmp1
    set +e
}
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
umount_ramdisk() {

    # put contents of ramdisk back to original location on harddisk

    disk=$1
    ram=${disk}-in-ramdisk

    # test, if a ramdisk is mounted to this directory 
    mount | grep -q " $1 type tmpfs"
    if [ $? -eq 1 ]; then
	echo "$d is not a mounted ramdisk."
	return
    fi

    set -e
    mkdir $ram
    mount --move $disk $ram   # move current ramdisk to a new location
    rm -rf $disk
    cp -a  $ram $disk   # copy ramdisk contents to disk
    umount $ram
    echo "Ramdisk on $d umounted"
    rmdir  $ram
    set +e
}
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

size= # no default size
umount=0
useall=0

# mkramdisk



while getopts ans:u opt ; do
    case "$opt" in
    # -a: mount all dirs listed in FAI_RAMDISKS instead of dirs given as arguments
        a) useall=1 ;;
        u) umount=1 ;;       # umount instead of mount
        s) size="-o size=$OPTARG" ;; # give size of ramdisk
        n) mtab="-n" ;;      # do not wirte to /etc/mtab
        esac
done
shift $(($OPTIND - 1))

if [ -n "$FAI_NORAMDISK" ]; then
    echo "The use of \$FAI_NORAMDISK is now deprecated. Please use \$FAI_RAMDISKS instead."
    exit 99
fi

# set default dirs if FAI_RAMDISKS not already set
: ${FAI_RAMDISKS:="$target/var/lib/dpkg"}

# use arguments $@ unless -a was specified
[ $useall -eq 0 ] && FAI_RAMDISKS=$@

for d in $FAI_RAMDISKS; do
    if [ $umount -eq 1 ]; then
	umount_ramdisk $d
    else
	[ -d "$d" ] && mount_ramdisk $d $size $mtab
    fi
done
