#!/bin/sh
# SPDX-License-Identifier: GPL-2.0-or-later
# First-boot grow of the STORAGE partition to fill the host disk, in
# place — STORAGE is our root filesystem (root=PARTLABEL=STORAGE).
#
# Triggered by the presence of /storage/.please_resize_me — our
# postinst.chroot stamps that on the freshly-imaged rootfs. The unit
# clears the marker once the resize succeeds so the next boot is a
# no-op.
#
# Three steps:
#   1. sgdisk -e <disk>      — move the backup GPT to the real end of
#                              the device (raw image is much smaller
#                              than the SD card it was dd'd onto).
#   2. parted resizepart     — extend the STORAGE partition to fill
#                              the freed space.
#   3. resize2fs <part>      — online ext4 resize.
#
# The original ROCKNIX fs-resize unmounted /storage and ran mke2fs.
# That's safe when /storage is empty user-data; it is *not* safe when
# /storage is the running rootfs.

set -eu

MARKER=/storage/.please_resize_me
LOG=/var/log/pocketds-fs-resize.log

[ -e "$MARKER" ] || exit 0

mkdir -p "$(dirname "$LOG")"
exec 3>>"$LOG"
date -Iseconds >&3
echo "pocketds-fs-resize starting" >&3

PART=$(blkid -t PARTLABEL=STORAGE -o device | head -n1)
if [ -z "$PART" ]; then
    echo "PARTLABEL=STORAGE not found, aborting" | tee /dev/console >&3
    rm -f "$MARKER"; sync
    exit 0
fi

case "$PART" in
    /dev/mmcblk*|/dev/nvme*) DISK="${PART%p[0-9]*}"; PARTNUM="${PART##*p}" ;;
    *)                       DISK="${PART%[0-9]*}";  PARTNUM="${PART##*[!0-9]}" ;;
esac

echo "DISK=$DISK PART=$PART PARTNUM=$PARTNUM" >&3

# Step 1 — fix the GPT backup header. Mandatory after dd'ing a smaller
# raw image onto a larger device; without this `parted resizepart`
# either prompts or refuses.
echo "moving backup GPT to end of $DISK" | tee /dev/console >&3
sgdisk -e "$DISK" >>$LOG 2>&1 || true

# Step 2 — extend the partition. parted's `-f` (fix prompts) handles
# any remaining mismatch quirks.
echo "growing $PART to fill $DISK" | tee /dev/console >&3
parted -s -f "$DISK" resizepart "$PARTNUM" 100% >>$LOG 2>&1

# Re-read partition table so the kernel sees the new partition size.
partprobe "$DISK" >>$LOG 2>&1 || true

# Step 3 — online ext4 resize. ext4 supports growing a mounted
# filesystem; no unmount needed.
echo "online-resizing $PART" | tee /dev/console >&3
resize2fs "$PART" >>$LOG 2>&1

# Drop the marker only after all three steps succeed so a partial
# failure leaves it for the next boot to retry.
rm -f "$MARKER"
sync

echo "resize complete" | tee /dev/console >&3
