#! /bin/sh

# 01scripted-partitioning runs quite early in the finish-install phase:
# before the 02* and following because it needs to set up the /var/cache symlink
# but later than 01scripted-crypto because it needs the encrypted volumes
#
# See run-parts(1) for details on ordering

set -e

echo tmpfs /tmp tmpfs defaults,size=20G,mode=1777 0 0 >> /target/etc/fstab
chroot /target mount /tmp

getsize () {
    chroot /target df --output=size -m $1 | tail -n +2
}

for old in /var/cache /home /opt ; do
    new=$(echo $old | sed -e s,^/,, -e s,/,-,g)
    vol=local00
    if [ $old = "/opt" ] \
       && [ -e /target/local01 ] ; then
	s00=$(getsize /local00)
	s01=$(getsize /local01)
	if [ "$s01" -gt "$s00" ] ; then
	    vol=local01
	fi
    fi
    new=/$vol/$new
    logger "Moving $old to $new and setting up bindmount"
    chroot /target mv $old $new
    echo "$new $old none bind,nofail 0 0" >> /target/etc/fstab
    mkdir -p /target/$old
    chroot /target mount $old
done
