#!/bin/bash
# This script allows flushing of the permanent storage to a .lzm file,
# allowing for some more space

DST="/mnt/cdrom/modules"
# make sure this is the last filename
DSTFILE="zz_changes"
CHANGESDIR="/mnt/overlay/.upper"
#CHANGESDIR="/.unions/memory/aufs-rw-branch/default/"

#gentoo-functions uses "consoletype" which returns non-zero exit codes on success
#the cleanest way to handle this is to never "set -e" before sourcing gentoo-functions
source /lib/gentoo/functions.sh

set -e

usage ()
{
	echo
	echo "   Usage : flushchanges [dest]"
	echo "   Where [dest] is the modules storage directory"
	echo "   defaulting to ${DST}"
	echo
}

squash ()
{
	if ! mount | grep -q "${CHANGESDIR}"
	then
		eerror "It appears that you're not using unionfs/aufs/overlayfs"
		return 1
	else
		mksquashfs "${CHANGESDIR}" "$1" -comp xz -Xbcj x86 -b 1048576 -no-recovery -noappend -Xdict-size 1048576
		return $?
	fi
}

if [ ! -z "$1" ]
then
	DST=$1
fi

echo "Using ${DST} for module storage"

if [ ! -e "${DST}" ]
then
	ewarn "Unable to find module dir ${DST}"
	usage
	exit 1
else
	index=0
	while true
	do
		indexstring="0${index}"
		indexstring="${indexstring:(-2)}"
		if [ ! -f "${DST}/${DSTFILE}-${indexstring}.lzm" ]
		then
			if squash "${DST}/${DSTFILE}-${indexstring}.lzm"
			then
				einfo "$DST/${DSTFILE}-${indexstring}.lzm created successfully"
				break
			else
				eerror "Unable to create $DST/${DSTFILE}-${indexstring}.lzm"
				exit 1
			fi
		fi
		index=$((index + 1))
	done
fi
