#!/bin/sh

ROOT=$1

fail() { echo "growroot: FAIL:" "$@"; }
msg() { echo "$@"; }

# figure out what disk ROOT is on
{ [ ! -L "${ROOT}" ] && rootdev=${ROOT} || rootdev=$(readlink -f "${ROOT}") ; } ||
	fail "failed to get target of link for ${ROOT}"

case "${rootdev}" in
	*[0-9]) : ;;
	# the root is a disk, not a partition (does not end in a digit)
	# no need to do anything in this case, kernel already knows the full size.
    *) exit 0;;
esac

# remove all consective numbers from the end of rootdev to get 'rootdisk'
rootdisk=${rootdev}
while [ "${rootdisk%[0-9]}" != "${rootdisk}" ]; do
	rootdisk=${rootdisk%[0-9]};
done
partnum=${rootdev#${rootdisk}}

# if the basename of the root device (ie 'xvda1' or 'sda1') exists
# in /sys/block/ then it is a block device, not a partition
# (xen xvda1 is an example of such a funny named block device)
[ -e "/sys/block/${rootdev##*/}" ] && exit 0

# if growpart fails, exit. its failure messages should go
# to stderr, so they'll get to the console
out=$(growpart "${rootdisk}" "${partnum}" ) ||
	{ msg "${out}"; exit 1; }

# if growpart output starts with 'CHANGED:' then it did something.
# anything else, exit
case "${out}" in
	CHANGED:*) echo "GROWROOT: $out";;
	*)
		echo "$out";
		exit 0;;
esac

was_mounted=false
while read src mp fstype opts o p; do
	if [ "$src" = "$ROOT" ]; then
		FS=$fstype;
		OPTS=$opts;
		MP=$mp
		was_mounted=true
	fi
done < /proc/mounts

if $was_mounted; then
	umount "${ROOT}" || fail "failed to umount ${ROOT}";
fi

sfdisk -R "${rootdisk}" ||
	msg "failed to re-read partition for ${rootdisk}"

if $was_mounted; then
	# this is taken from 'mountroot' function
	#   see /usr/share/initramfs-tools/scripts/local
	i=0
	while [ $i -lt 50 ]; do
		mount -o "$OPTS" "$ROOT" "$MP" >/dev/null 2>&1 && exit 0
		i=$(($i+1))
		sleep .2
	done
	[ $i -eq 50 ] && fail "unable to remount, that is bad"
fi

# write to /etc/grownroot-grown. most likely this wont work (readonly)
{ date --utc > "${rootmnt}/etc/growroot-grown" ; } >/dev/null 2>&1 || :

# vi: ts=4 noexpandtab
