#!/bin/sh

# swap size multiplicator (static for now)
SWAP_MUL=1

# root size multiplicators against the actual one for a LiveCD (if any)
ROOT_MUL_MIN=3/2
ROOT_MUL_MAX=40

# values below in gigabytes, might be natural fractions
SWAP_MAX=8
ROOT_MIN=1 # this is integer (or improve the comparison below)
ROOT_SIZE=5
HOME_SIZE=1/2 # this will be marked to fill up free space

# recalculate in kilobytes
SWAP_MAX=$[1048576*$SWAP_MAX]
ROOT_MIN=$[1048576*$ROOT_MIN]
ROOT_SIZE=$[1048576*$ROOT_SIZE]
HOME_SIZE=$[1048576*$HOME_SIZE]

# swap == RAM (but not more than $SWAP_MAX Gb)
swap_size="$[`grep MemTotal /proc/meminfo | sed 's/[^0-9]//g'`*$SWAP_MUL]"
[ "$swap_size" -gt "$SWAP_MAX" ] && swap_size="$SWAP_MAX"

# don't do RAID in a VM, reduce swap to a minimum, root to reasonable
if grep -qE "(101300b8)|(80eebeef)|(14ad0405)" /proc/bus/pci/devices; then
	methods="plain"
	swap_size=131072	# 128M
	ROOT_MUL_MAX=10
else
	methods="raid plain"
fi

# are we running off a LiveCD as a part of livecd-install?
if [ -d /.ro ]; then
	root_size="`df -Pk /.ro | tail -1 | { read d t u rest; echo "$u"; }`"
	[ "$root_size" -lt "$ROOT_MIN" ] && root_size="$ROOT_MIN"
	root_min="$[$root_size*$ROOT_MUL_MIN]"
	root_max="$[$root_size*$ROOT_MUL_MAX]"
else
	root_min="$[1048576*$ROOT_SIZE]"
	root_max="$[$root_min*$ROOT_MUL_MAX]"
fi

# recalculate in 512-byte blocks for EVMS
swap_size="$[$swap_size*2]"
home_size="$[$HOME_SIZE*2]"
root_min="$[$root_min*2]"
root_max="$[$root_max*2]"

max_disk="$(sort -rn /sys/block/[hs]d*/size | head -1)" # in 512-byte sectors
if [ -n "$max_disk" ]; then
	root_cap="$[$max_disk-4*$home_size-$swap_size]"
	[ "$root_max" -gt "$root_cap" ] && root_max="$root_cap"
fi

if [ "$root_min" -gt "$root_max" ]; then
	root_max="$root_min"
	swap_size=32	# 16M
fi

cat > /var/cache/alterator/vm-profile.scm << _EOF_
((workstation
  (title . "Setup for workstation")
  (action . trivial)
  (actiondata
   ("swap"  (size 0 . $swap_size) (fsim . "SWAPFS") (methods plain))
   ("/"     (size $root_min . $root_max ) (fsim . "Ext2/3") (methods plain))
   ("/home" (size $home_size . #t) (fsim . "Ext2/3") (methods $methods)))))
_EOF_
