get_mem () {
	local ram=$(grep ^MemTotal: /proc/meminfo | { read x y z; echo $y; }) || true # in kilobytes
	if [ -z "$ram" ]; then
		echo "Cannot determine system memory" >&2
        	ram=0
	else
	        ram=$(expr "$ram" / 1024) # convert to megabytes
	fi
	echo $ram
}

check_gtk () {
	if [ -z "$TERM_FRAMEBUFFER" ] ; then
		echo "Framebuffer not available; disabling graphical frontend" >&2
		return 1
	fi
	if [ "$GTK_NOVESA" ]; then
		echo "No VESA framebuffer available; disabling graphical frontend" >&2
		return 1
	fi

	case "$(archdetect)" in
	    powerpc/*)
		local MEMLIMIT=122 ;;	# is 128 MiB
	    *)
		local MEMLIMIT=88 ;;	# is 92 MiB
	esac

	if [ $(get_mem) -lt $MEMLIMIT ] ; then
		echo "Insufficient memory for graphical frontend; disabling" >&2
		return 1
	fi
	return 0
}

if [ -z "$DEBIAN_FRONTEND" ] ; then
	for frontend in gtk newt slang text ; do
		if [ -e "/usr/lib/cdebconf/frontend/$frontend.so" ]; then
			if [ "$frontend" = gtk ] ; then
				check_gtk || continue
			fi
			DEBIAN_FRONTEND=$frontend
			break
		fi
	done
fi
export DEBIAN_FRONTEND
