#!/usr/bin/env bash

## of-expand v2.04 (28th April 2026)
##  Expands the root partition and filesystem to fill the drive.

if [ "$USER" != "root" ] && [ "$USER" != "" ]; then
	echo "You need to run this with superuser privileges. Try 'sudo $0'."
	exit 1
fi

show_status() {
	{
		printf "\033[2J\033[H\n"
		printf "  ┌──────────────────────────────────────────────────────────────────────────────────────────────┐\n"
		printf "  │  %-90s  │\n" "$1"
		printf "  │  This can take a few minutes, please do not power off.                                       │\n"
		printf "  └──────────────────────────────────────────────────────────────────────────────────────────────┘\n"
		printf "\n"
	} > /dev/tty1
}

ROOTDEV=$(findmnt -n -o SOURCE /)
ROOTPARTNO="${ROOTDEV: -1}"
[[ "$ROOTDEV" =~ "mmc" ]] && DISKDEV="${ROOTDEV::-2}" || DISKDEV="${ROOTDEV::-1}"

echo "Root is on $ROOTDEV (disk: $DISKDEV, partition: $ROOTPARTNO)."

# Remove tmpfs fstab entries.
sed -i '/\/var\/cache\/apt/d' /etc/fstab
sed -i '/\/var\/lib\/apt\/lists/d' /etc/fstab
sed -i '/\/tmp/d' /etc/fstab

show_status "Expanding partition..."
TMPDIR=/run growpart $DISKDEV $ROOTPARTNO > /dev/null
GPRET=$?
if [ $GPRET -eq 1 ]; then
	echo "Partition already at maximum size."
elif [ $GPRET -ne 0 ]; then
	echo "growpart failed (exit $GPRET). Skipping filesystem resize."
	exit 1
fi

show_status "Expanding filesystem..."
resize2fs $ROOTDEV > /dev/null

echo "Done."

exit 0
