#!/bin/sh
# analyze free space, preferring tmpfs over really many gigaz
# and taking into account configured hasher workdir prefices

# NB: use BUILDDIR to override autodetection (see ../QUICKSTART)

# hope there aren't spaces in RM's $HOME are they?
DIRS="$TMP $TMPDIR $HOME/hasher /tmp /var/tmp .."
MINSIZE=262144		# face control criterion

# mkimage needs /proc among those, be clear about that
check_allowed_mountpoints()
{
	grep -wqs "^allowed_mountpoints=[^#]*/proc" \
		/etc/hasher-priv/system \
		`/usr/libexec/hasher-priv/getconf.sh`
}

# poor man's SourceIfExists()
try_source() { [ -f "$1" ] && . "$1"; }

# hasher accepted ones
get_prefices()
{
	try_source /etc/hasher-priv/system || exit 1
	try_source `/usr/libexec/hasher-priv/getconf.sh`
	echo "$prefix" | tr ':' '\n' | while read i; do realpath "$i"; done
}

# drop candidates that hasher won't handle anyways
# NB: doesn't take --number into account,
# prefix lists are defined by the primary configuration
contemplate_dirs()
{
	for d in "$@"; do
		D="`realpath "$d"`";
		for p in `get_prefices`; do
			[ "${D#$p}" = "$D" ] || echo "$D";
		done;
	done \
	| uniq	# _not_ sort -u
}

# hasher emits no meaningful errors regarding those, sigh
check_options()
{
	! grep -E -q "^$1 $2 .*no(dev|exec)" /proc/mounts
}

# pick existing, writeable, >256M free space dirs
# rank them wrt type: tmpfs > realfs > rootfs
choose_tmpdir() {
	for i in "$@"; do
		[ -d "$i" -a -w "$i" ] || continue
		echo -n "$i "
		df -PT "$i" | tail -1
	done \
	| sort -unk5 \
	| while read dir dev fstype size used free percent mnt; do
		check_options "$dev" "$mnt" || continue
		[ "$free" -gt "$MINSIZE" ] || continue
		[ "$fstype" = "tmpfs" ] && { echo "2 $dir $free"; continue; }
		[ "$mnt" = "/" ] && { echo "0 $dir $free"; continue; }
		echo "1 $dir $free"
	done \
	| sort -n \
	| tail -1 \
	| cut -f2 -d' '
}

# bringing it all together
if ! check_allowed_mountpoints; then
	echo "error: hasher's allowed_mountpoints do not include /proc;"
	echo "please check hasher docs and /etc/hasher-priv/system"
	exit 1
fi >&2

TMPDIRS="`contemplate_dirs $DIRS`"
if [ -z "$TMPDIRS" ]; then
	echo "error: no suitable directories found;"
	echo "please check QUICKSTART, filesystem and hasher setup"
	echo "(mount enough tmpfs into /tmp or fix hasher-priv prefix?)"
	exit 1
fi >&2

TEMP="`choose_tmpdir $TMPDIRS`"
if [ -z "$TEMP" ]; then
	echo "error: no suitable directories found;"
	echo "please check hasher docs and filesystem setup"
	echo "(nodev and/or noexec on an otherwise suitable filesystem?)"
	exit 1
fi >&2

DIR="$TEMP/`dirname "$1"`"
NAME="`basename "${1:-tmpdir}"`"
mkdir -p "$DIR"	# in case $1 contains slash(es)
mktemp -d "$NAME.XXXXXXX" --tmpdir="${DIR%/.}"