#!/bin/sh
########################################################################
# Begin $rc_base/init.d/partresize
#
# Description : Resize the root partition to the drivesize
#
# Authors     : Arne Fitzenreiter - arne_f@ipfire.org
#
# Version     : 1.04
#
# Notes       :
#
########################################################################

. /etc/sysconfig/rc
. ${rc_functions}

case "${1}" in
	start)
		if [ -e "/.partresize" ]; then
			boot_mesg "Mounting root file system in read/write mode ..."
			mount -o remount,rw / > /dev/null
			evaluate_retval

			boot_mesg "Create /etc/mtab..."
			> /etc/mtab
			mount -f / || failed=1
			(exit ${failed})
			evaluate_retval

			# Detect device
			mount | while read -r dev tmp1 mountpoint tmp2; do
				[ "${dev}" = "rootfs" ] && continue

				if [ "${mountpoint}" = "/" ]; then
					# Find root partition number
					part_num="${dev: -1}"

					# Find path to the root device
					root_dev="${dev::-1}"
					if [ ! -b "${dev::-1}" -a "${root_dev: -1}" = "p" ]; then
						root_dev="${dev::-2}"
					fi

					boot_mesg "Growing root partition to maximum size..."
					echo -e ',+' | sfdisk --no-reread -f -N${part_num} "${root_dev}" 2>/dev/null

					# Update c,h,s values of the boot partition...
					if [ ${part_num} -ne 1 -a -b "${root_dev}1" ]; then
						echo -e ',' | sfdisk --no-reread -f -N1 ${DRV} &> /dev/null
					fi

					# The filesystem should be resized after
					# this operation
					touch /.resizefs

					# Remove marker
					rm -f /.partresize

					# Reboot
					boot_mesg "Rebooting system..."
					mount -o remount,ro / &>/dev/null
					sleep 15
					reboot -f
				fi
			done
		fi
		;;
	*)
		echo "Usage: ${0} {start}"
		exit 1
		;;
esac

# End $rc_base/init.d/partresize
