#!/bin/sh
# Resize rootfs after booting. Based on growroot.sh and growroot from cloud-initramfs-tools

set -e

passphrase=""
rootmnt="/"

msg() { echo "resize_rootfs:" "$@" ; }
fail() { [ $# -eq 0 ] || msg "$@"; exit 1; }

# if a file indicates we should do nothing, then just exit
[ -f "${rootmnt}/etc/resize_rootfs-disabled" ] && echo "Not doing anything (disabled by /etc/resize_rootfs-disabled)" && exit 0

if [ $# = 1 ]; then
        passphrase=$1
        if [ "${passphrase}" = "-h" ]; then
                echo "usage: $0 [passphrase]"
                exit 0
        fi
fi

# Get the root device, root filesystem and mount options
if ! out=$(awk '$2 == mt { print }' "mt=${rootmnt}" < /proc/mounts) ; then
	fail "${out}"
	return
fi

# Need to do it this way, can't use '<<< "${out}"' since dash doesn't
# seem to understand it
read rootdev _rootmnt _rootfs _opts unused <<EOF
${out}
EOF

# Check if rootfs is on a luks device and resize that if possible
if [ -x /sbin/dmsetup ] && [ -x /sbin/cryptsetup ]; then
	if [ -n "$(dmsetup status --target crypt ${rootdev})" ]; then
		if [ -n "$passphrase" ]; then
			echo "${passphrase}" | cryptsetup resize "${rootdev}"
		else
			cryptsetup resize "${rootdev}"
		fi
	fi
fi

set +e
out=$(resize2fs "${rootdev}" 2>&1)
set -e
ret=$?

case "$ret" in
	0) msg "succeeded"; touch /etc/resize_rootfs-resized;;
	*) fail "failed '$ret'" "${out}";;
esac

# Resize and format the swap file (for hibernate) now that the partition is
# resized.  The image builder creates a 1 MiB swap file so the physical offset
# of the first extent is known.
if SWAPFILE_SIZE="$(stat -c %s /swapfile 2>/dev/null)" && [ "$SWAPFILE_SIZE" -le $((1024*1024)) ]; then
	fallocate -l 10G /swapfile
	mkswap /swapfile
	# Enable this file as swap and start it.  Done manually for the first boot since
	# systemd swap units do not wait on local-fs.target, and we can't grow the swap
	# file until root is resized.  The image builder already configured this file as
	# the resume device.
	echo '/swapfile none swap defaults 0 0' >>/etc/fstab
	swapon /swapfile
fi
