#!/bin/sh

. /etc/image_features


TMPFS_DESTTIMEOUT=$((30*60))
TMPFS_SIZE=$((24*1024*1024))

if [ "$HW_TYPE" == HW_TYPE_PC ]; then
    totalMem=$(awk '/MemTotal/ { print $2 }' /proc/meminfo) #KB
    if [ $totalMem -ge 4000 ]; then
        s=$(echo "12.5*$totalMem/100" | bc) #KB
        TMPFS_SIZE=$(($s*1024))
    fi
fi

SCRIPT_NAME=${0##*/}
TMPFS_DEV=/dev/ram1
TMPFS_MNT=/tmp/limitedstorage

LOCK_FILE=/tmp/mklimstorage.lock

SUCCESS=0
ERR_LOCK=1
ERR_LOCK_WAIT_TIMEOUT=2

create()
{
    if isLocked; then
	if ! waitForUnlock; then
	    return $ERR_LOCK_WAIT_TIMEOUT
	fi
    fi
    
    lock
    if [ -z "$(/bin/mount -t tmpfs | grep $TMPFS_MNT)" ] ; then
        /bin/mkdir $TMPFS_MNT > /dev/null 2>&1
        /bin/mount $TMPFS_DEV $TMPFS_MNT -t tmpfs -o size=$1 > /dev/null 2>&1
    fi
    unlock
    
    return $?
}

cleanup()
{
    killProcesses

    if isLocked; then
	if ! waitForUnlock; then
	    return $ERR_LOCK_WAIT_TIMEOUT
	fi
    fi

    lock
    /bin/umount $TMPFS_MNT > /dev/null 2>&1
    /bin/rm -rf $TMPFS_MNT
    unlock
    
    return $?
}

killInstances()
{
    if isLocked; then
	if ! waitForUnlock; then
	    return $ERR_LOCK_WAIT_TIMEOUT
	fi
    fi
    
    lock
    for pid in $(/sbin/pidof -x $SCRIPT_NAME); do
	if [ "$pid" != "$$" ]; then
	    /bin/kill $pid > /dev/null 2>&1
	fi
    done
    unlock
    
    return $?
}

killProcesses()
{
    /usr/bin/killall tcpdump > /dev/null 2>&1
}

lock()
{
    if isLocked; then
	return $ERR_LOCK
    fi
    
    echo > $LOCK_FILE
    
    return $SUCCESS
}

unlock()
{
    if ! isLocked; then
	return $ERR_LOCK
    fi
	
    rm -f $LOCK_FILE
    
    return $SUCCESS
}

isLocked()
{
    if [ -f $LOCK_FILE ]; then
	return 0
    else
	return 1
    fi
}

waitForUnlock()
{
    tryCount=3
    timeout=1

    while isLocked; do
	if [ $tryCount = 0 ]; then
	    return $ERR_LOCK_WAIT_TIMEOUT
	fi
	
	tryCount=$(($tryCount-1))

	/bin/sleep $timeout
    done
    
    return $SUCCESS
}

killInstances

case "$1" in 
    create)
	if [ $2 ]; then
	    TMPFS_SIZE=$2
	fi
	
	create $TMPFS_SIZE
	;;
    cleanup)
	if [ $2 ]; then
	    TMPFS_DESTTIMEOUT=$2
	fi
	
	/bin/sleep $TMPFS_DESTTIMEOUT
	cleanup
	;;
    *)
	echo "Usage: $0 {create [size(bytes)] | cleanup [timeout(sec)]}"
	exit 1
esac

exit $?
