#!/bin/sh
set -e

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

. /scripts/functions

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

###
### This runs before the root filesystem is mounted, so we can fiddle with
### the partition table without fearing to break anything
###

[ -f /etc/resized-rootfs ] && exit 0

# Don't do anything when using an unencrypted rootfs, growroot is enough
if echo $ROOT | grep -q "/dev/mapper"; then
    volname=$(basename $ROOT)

    # /dev/mapper/<volume> doesn't exist yet as we run before cryptroot,
    # so we have to retrieve the physical partition's UUID in crypttab
    partuuid=$(grep "$volname" /cryptroot/crypttab | sed 's/^.*UUID=\([^ ]*\).*$/\1/')

    rootpart=$(lsblk -n -o kname,uuid | grep "${partuuid}" | awk '{ print $1 }')
    rootdev=$(lsblk -n -s -o kname,type /dev/${rootpart} | grep 'disk' | awk '{ print $1 }')
    partnum=$(echo ${rootpart} | sed "s/${rootdev}p\?//")

    if [ -b /dev/$rootdev ]; then
        growpart /dev/$rootdev $partnum
    fi
fi
