#!/bin/bash
#
# Expand rootfs to fill available eMMC space on Qualcomm boards
# Removes empty userdata partition and grows rootfs to use all remaining space
#

DISK=/dev/mmcblk0
ROOTPART=68
FLAG=/var/lib/.rootfs-expanded

# Only run once
[ -f "$FLAG" ] && exit 0

# Remove empty userdata partition (69) if present
sgdisk -d 69 "$DISK" 2>/dev/null

# Move backup GPT to end of disk
sgdisk -e "$DISK"

# Get current start sector of rootfs
STARTLBA=$(sgdisk -i "$ROOTPART" "$DISK" | grep "First sector" | awk '{print $3}')

# Recreate rootfs using all remaining space
sgdisk -d "$ROOTPART" \
	-n "${ROOTPART}:${STARTLBA}:0" \
	-t "${ROOTPART}:8305" \
	-c "${ROOTPART}:rootfs" \
	"$DISK"

partprobe "$DISK"
resize2fs "${DISK}p${ROOTPART}"

touch "$FLAG"
