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

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

	# Set level1 to the minimum amount of memory that will support an
	# install not in lowmem mode. (This is the max memory footprint of
	# the installer in non lowmem mode up to running the partitioner
	# and swapon.)
	# Set level2 to the minimum amount of memory that will support an
	# install in lowmem mode. (This is the max memory footprint of the
	# installer in lowmem mode up to running the partitioner
	# and swapon.)
	# Set min to absolute minimum of memory needed for an install.
	ARCH=`udpkg --print-architecture`
	case $ARCH in
		alpha)
			level1=82
			level2=55
			min=39
		;;
		arm|armel)
			level1=60 # not sure but more than 32
			level2=33
			min=18
		;;
		armeb)
			level1=60 # not sure but more than 32
			level2=24
			min=18
		;;
		i386|amd64)
			level1=72 # MT=74304, VMware=76 (auto-LVM works)
			level2=36 # MT=37776, VMware=40
			min=28    # MT=29672, VMware=32
		;;
		mips)
			level1=57
			level2=33
			min=21
		;;
		mipsel)
			level1=60
			level2=33
			min=19
		;;
		m68k)
			level1=64
			level2=32
			min=0 #FIXME
		;;
		s390)
			level1=44 # needs MAINSIZE=48 in Hercules
			level2=28
			min=20
		;;
		*)
			level1=64
			level2=32
			min=0 #FIXME
		;;
	esac

	if [ "$ram" -lt "$level1" ]; then
		echo "Entering low memory mode, please wait ..."

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