ram=$(grep ^MemTotal: /proc/meminfo | { read x y z; echo $y; }) || true # in kilobytes

if [ -z "$ram" ]; then
	echo "Cannot determine system memory, skipping lowmem probe" >&2
else
	ram=$(expr $ram / 1024) # convert to megabytes

	# See README in lowmem source on how to update these levels
	ARCH=$(udpkg --print-architecture)
	case $ARCH in
		alpha)
		# Update needed
			level1=82
			level2=55
			min=39
		;;
		amd64)
			level1=71 # MT=72976, qemu: -m 80
			level2=67 # MT=68880, qemu: -m 76
			min=51    # MT=52496, qemu: -m 60
		;;
		arm|armel)
			level1=32 # MT=32792, qemu: -m 36
			level2=28 # MT=28752, qemu: -m 32
			min=24
		;;
		armeb)
			level1=32 # MT=32792, qemu: -m 36
			level2=21
			min=18
		;;
		i386)
			level1=51 # MT=52416, qemu: -m 56
			level2=51 # MT=52416, qemu: -m 56
			min=39    # MT=40224, qemu: -m 44
		;;
		mips)
		# Update needed
			level1=57
			level2=33
			min=21
		;;
		mipsel)
		# Update needed
			level1=60
			level2=33
			min=19
		;;
		m68k)
		# Update needed
			level1=64
			level2=32
			min=0 #FIXME
		;;
		s390)
		# Update needed
			level1=44 # needs MAINSIZE=48 in Hercules
			level2=28
			min=20
		;;
		sh4)
		# Update needed
			level1=41
			level2=36
			min=28
		;;
		*)
			level1=64
			level2=32
			min=0 #FIXME
		;;
	esac

	use_level=0
	if  [ $ram -lt $min ]; then
		use_level=9
	elif [ $ram -lt $level2 ]; then
		use_level=2
	elif [ $ram -lt $level1 ]; then
		use_level=1
	fi

	# Check for lowmem level set by user; only 1 and 2 supported
	# We cannot use preseeding yet, so parse /proc/cmdline directly
	user_level=$(grep "lowmem=[12]" /proc/cmdline | \
			sed "s/^.*lowmem=\([0-9]*\).*$/\1/")
	if [ "$user_level" ] && [ $user_level -gt $use_level ]; then
		logger -t lowmem "Using $user_level instead of default level $use_level"
		use_level=$user_level
	fi

	if [ $use_level -gt 0 ]; then
		logger -t lowmem "Entering low memory mode"

		if [ $use_level -le 2 ]; then
			echo $use_level > /var/lib/lowmem
		else
			echo 2 > /var/lib/lowmem
			# 4 mb fuzz for kernel
			echo "$(($min + 4))" > /var/lib/lowmem_insufficient
		fi
		
	       	trimtemplates /var/lib/dpkg/info || true
	fi
fi
