#!/bin/sh
set -e

PREREQS="growroot"
case $1 in
    prereqs) echo "${PREREQS}"; exit 0;;
esac

. /scripts/functions

msg() { log_success_msg "RESIZE-ROOTFS: $@" ; }
fail() { [ $# -eq 0 ] || log_failure_msg "$@"; exit 1; }

###
### This runs right before exec of /sbin/init. The real root is
### already mounted at rootmnt
###

# if a file indicates we should do nothing, then just exit
for file in /etc/resize-rootfs-disabled /etc/resized-rootfs; do
	[ -f "${rootmnt}${file}" ] && exit 0
done

plymouth --ping &&
plymouth message --text="Resizing file system during initial boot"

# this is taken from 'mountroot' function
#   see /usr/share/initramfs-tools/scripts/local
if [ -z "${ROOTFSTYPE}" ]; then
    FSTYPE=$(get_fstype "${ROOT}")
else
    FSTYPE=${ROOTFSTYPE}
fi

if [ ${FSTYPE} = "btrfs" ]; then
    # BTRFS requires FS to be mounted
    /bin/btrfs filesystem resize max ${rootmnt} || fail "failed to resize ${ROOT} with fs ${FSTYPE}"
else
    # There was something to do, unmount and resize
    umount "${rootmnt}" || fail "failed to umount ${rootmnt}";

    case ${FSTYPE} in
        f2fs) RESIZE_CMD="/sbin/resize.f2fs";;
        ext*) RESIZE_CMD="/sbin/resize2fs -f";;
    esac

    if [ "${RESIZE_CMD}" ]; then
        ${RESIZE_CMD} ${ROOT} || fail "failed to resize ${ROOT} with fs ${FSTYPE}"
    fi

    roflag="-r"
    [ "${readonly}" = "y" ] || roflag="-w"
    mount ${roflag} ${FSTYPE:+-t ${FSTYPE} }${ROOTFLAGS} ${ROOT} ${rootmnt} ||
        fail "failed to re-mount ${ROOT}. this is bad!"
fi

touch "${rootmnt}/etc/resized-rootfs"

plymouth --ping &&
plymouth message --text=""
