#!/bin/sh
# vim: set ts=4:
#
# Note: This script does not increase size of underlying partitions,
# because it's just silly to use partitions on non-physical disks.
set -eu

# Prints size of the specified device in megabytes.
dev_size() {
	local dev_path="$1"

	local bytes="$(blockdev --getsize64 "$dev_path")"
	expr $bytes / 1024 / 1024
}

resize_ext() {
	local dev_path="$1"

	# Note: df doesn't count reserved blocks, that's why we use dumpe2fs.
	local fs_size="$(dumpe2fs -h "$dev_path" 2>/dev/null \
					| sed -En 's/Block (count|size):\s*([0-9]+)/\2/p' \
					| xargs | awk '{ print int($1 * $2 / 1024 / 1024) }')"
	local dev_size="$(dev_size "$dev_path")"

	if [ -z "$fs_size" ] || [ -z "$dev_size" ]; then
		echo "WARN: Failed to get size of FS or device $dev_path" >&2

	elif [ $fs_size -lt $dev_size ]; then
		echo "Resizing FS on $dev_path from $fs_size MiB to device size $dev_size MiB" >&2
		resize2fs "$dev_path"
	fi
}


#-------------------------------- Main -------------------------------

if [ -n "${GROWFS_DISABLE:-}" ]; then
	exit 0
fi

mount | cut -d' ' -f1,5 | sort | uniq | while read dev_path fs_type; do
	case "$fs_type" in
		# Note: ext2 can't be resized online.
		ext3 | ext4)
			resize_ext "$dev_path"
		;;
	esac
done
