#!/usr/bin/bash
#
# Grow the root partition and filesystem to fill the medium.
#
# The image is built at a fixed size so the artifact stays small; whatever it
# gets written to is almost always bigger. Runs once, then disables itself.

set -euo pipefail

STAMP=/var/lib/c630/growfs-done

root_src="$(findmnt -no SOURCE /)"
root_dev="$(basename "$root_src")"

part_num_file="/sys/class/block/${root_dev}/partition"
if [ ! -r "$part_num_file" ]; then
    echo "c630-growfs: / is on ${root_src}, which is not a partition — nothing to grow"
    mkdir -p "$(dirname "$STAMP")" && touch "$STAMP"
    exit 0
fi

part_num="$(cat "$part_num_file")"
disk="/dev/$(lsblk -no pkname "$root_src")"

# The image was written with dd, so the secondary GPT header is still sitting
# where the end of the image used to be. growpart refuses to touch a disk in
# that state, so move it to the real end of the device first.
sgdisk --move-second-header "$disk" || true

if growpart "$disk" "$part_num"; then
    echo "c630-growfs: grew ${disk}${part_num}"
else
    # growpart exits non-zero with NOCHANGE when the partition already fills
    # the disk. That is a success for our purposes.
    echo "c630-growfs: partition already at full size"
fi

partprobe "$disk" || true
resize2fs "$root_src"

mkdir -p "$(dirname "$STAMP")"
touch "$STAMP"
echo "c630-growfs: done"
