#!/bin/sh
# NB: -f prohibited in this shebang
# check relevant kernel features availability

CONFIGS=/boot/config-*
GZ_OPTS="-comp gzip -noI"
XZ_OPTS="-comp xz"
LZO_OPTS="-comp lzo -noI"

verbose() { [ -z "$GLOBAL_VERBOSE" ] || echo "** $@" >&2; }
fatal() { echo "** error: $@" >&2; exit 1; }

configured()
{
	local option="CONFIG_$1"
	if grep -q "^$option" $CONFIGS; then
		verbose "${option%=*} available"
		return 0
	else
		return 1
	fi
}

ls $CONFIGS >&/dev/null || fatal "no stage1 kernel config found in /boot"

# test for installer-required filesystems support
for opt in SQUASHFS AUFS_FS OVERLAY_FS $GLOBAL_STAGE1_KCONFIG; do
	[ "$opt" = AUFS_FS ] && [ $(configured "OVERLAY_FS=[my]") -a $(configured "AUFS_FS=n") ] && continue
	configured "$opt=[my]" || fatal "stage1 kernel must have $opt support"
done

verbose "GLOBAL_SQUASHFS: $GLOBAL_SQUASHFS"

options()
{
	# squashfs options: not really neccessary but better than none
	# NB: this config file should be carried over into install2
	if [ "$GLOBAL_SQUASHFS" != "fast" ] && configured "SQUASHFS_XZ=y"; then
		# NB: the decompression filter overhead might hurt
		# NB: there are arm, powerpc and some other filters too
		if [ "$GLOBAL_SQUASHFS" = "tight" ] && configured "X86"; then
			XZ_OPTS="$XZ_OPTS -b 524288 -Xbcj x86"
		else
			XZ_OPTS="$XZ_OPTS -b 262144 -noI"
		fi
		echo "$XZ_OPTS"
	else	# go fast, or even faster if possible
		if configured "SQUASHFS_LZO=y"; then
			echo "$LZO_OPTS"
		else	# safe default
			echo "$GZ_OPTS"
		fi
	fi
}

echo "PACK_SQUASHFS_OPTS=-no-recovery `options`" > /.image/squashcfg.mk
