#!/bin/bash
# from http://gentoo-wiki.com/TIP_Speeding_up_portage_with_tmpfs
# further adapted by teknohog
# tmpfs can use swap too

DIR=/var/tmp/portage
MEMSIZE=$(free -g | egrep -o "[0-9]+" | head -n1)G
mounted=false

export PORTAGE_BIN_PATH=/usr/lib/portage/python3.4

source /usr/lib/portage/python3.4/isolated-functions.sh
 
mounttmpfs() {
     mount -t tmpfs tmpfs -o size=$MEMSIZE $DIR
     mounted="true"
}

compile() {
     einfo "emerging ${*}"
          emerge ${*}
}

unmount() {
     ebegin "unmounting tmpfs"
	# Ensure umount success by killing hung processes.. this is
	# sometimes dangerous, better put into a separate script
	#HUNG="`fuser -m $DIR | grep '[0-9]\+'`"
	#if [ -n "$HUNG" ]; then
	#	kill -9 $HUNG
	#fi	

          umount -f $DIR
     eend $?
}

# 2016-07-01 basic and useful
if [ -z "$(mount | grep /usr/portage)" ]; then
    mount /usr/portage
fi

ebegin "Mounting $MEMSIZE of memory to $DIR"
if [ -z "$(mount | grep $DIR)" ]
then
     mounttmpfs
else
     eerror "tmpfs already mounted"
     exit 0
fi
eend $?

compile ${*}
 
if [ -n "$mounted" ]
then
     unmount
fi
