#!/bin/sh
# SPDX-License-Identifier: GPL-2.0-or-later
# First-boot grow of the STORAGE partition to fill the disk.
# Triggered by the presence of /storage/.please_resize_me — drop that file
# into /storage on a freshly-imaged device, the unit reboots into the
# resize, then deletes the marker.
#
# Adapted from ROCKNIX packages/sysutils/busybox/scripts/fs-resize but
# re-pathed for a Fedora layout (no /flash logging, no LibreELEC progress
# helpers) and aimed at a GPT (PARTLABEL=STORAGE) layout rather than the
# old MBR mmcblk0p2 assumption.

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

# Refuse to resize if the storage partition is already populated -- ROCKNIX
# keeps this guard to prevent accidental data loss when the marker is left
# behind by mistake.
if [ -d /storage/.config ] || [ -d /storage/.cache ] || [ -d /storage/roms ]; then
    rm -f "$MARKER"
    sync
    echo "Resizing not permitted: /storage already initialised" | tee /dev/console >&3
    sleep 5
    systemctl reboot
    exit 0
fi

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
    systemctl reboot
    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

LABEL=$(blkid -o value -s LABEL "$PART" 2>/dev/null || true)
UUID=$(blkid -o value -s UUID  "$PART" 2>/dev/null || true)

rm -f "$MARKER"
sync

# Unmount /storage and grow the partition+filesystem.
systemctl stop storage.mount 2>/dev/null || umount /storage 2>/dev/null || true

echo "growing $PART to fill $DISK" | tee /dev/console >&3
parted -s -f "$DISK" resizepart "$PARTNUM" 100% >>$LOG 2>&1

# Recreate ext4 (matches ROCKNIX semantics — first boot has no useful data).
mke2fs -F -q -t ext4 -m 0 \
    ${LABEL:+-L "$LABEL"} \
    ${UUID:+-U "$UUID"} \
    "$PART" >>$LOG 2>&1

e2fsck -f -p "$PART" >>$LOG 2>&1 || true

sync
echo "resize complete; rebooting" | tee /dev/console >&3
sleep 5
systemctl reboot
