#!/bin/bash
# /usr/bin/expand-rootfs.sh
# StellarMate - Universal root filesystem expansion
# Works for: SM-140 (ext4), SM-170/SM-130/SM-180 (Btrfs)

set -e

echo "=== StellarMate: Expanding root filesystem ==="

# Get the root mount source (may include btrfs subvolume)
ROOT_MOUNT="$(findmnt / -o source -n)"
echo "Root mount source: $ROOT_MOUNT"

# Extract just the block device (strip btrfs subvolume notation)
# Example: /dev/mmcblk0p2[/@system-2.0.0] -> /dev/mmcblk0p2
ROOT_PART="${ROOT_MOUNT%%\[*}"

ROOT_DEV="/dev/$(lsblk -no pkname "$ROOT_PART")"
PART_NUM="$(echo "$ROOT_PART" | grep -o "[[:digit:]]*$")"

echo "Root partition: $ROOT_PART"
echo "Root device: $ROOT_DEV"
echo "Partition number: $PART_NUM"

# Detect filesystem type
FS_TYPE=$(lsblk -no FSTYPE "$ROOT_PART")
echo "Filesystem type: $FS_TYPE"

# Verify we support this filesystem
if [ "$FS_TYPE" != "ext4" ] && [ "$FS_TYPE" != "btrfs" ]; then
   echo "ERROR: Unsupported filesystem type: $FS_TYPE"
   echo "This script supports ext4 and btrfs only"
   exit 1
fi

# Safety check: verify this is the last partition
LAST_PART_NUM=$(parted "$ROOT_DEV" -ms unit s p 2>/dev/null | tail -n 1 | cut -f 1 -d:)
if [ "$LAST_PART_NUM" != "$PART_NUM" ]; then
   echo "WARNING: $ROOT_PART (partition $PART_NUM) is not the last partition (last is $LAST_PART_NUM)"
fi

# Check if growpart is available
if ! command -v growpart &> /dev/null; then
   echo "ERROR: growpart not found. Install: pacman -S cloud-guest-utils"
   exit 1
fi

# Check current partition size
PART_SIZE_BEFORE=$(lsblk -bno SIZE "$ROOT_PART")
echo "Current partition size: $(numfmt --to=iec-i --suffix=B $PART_SIZE_BEFORE)"

# Expand partition
echo "Expanding partition $PART_NUM on $ROOT_DEV..."
if growpart "$ROOT_DEV" "$PART_NUM"; then
   echo "Partition expanded successfully"
   EXPANDED=1
elif [ $? -eq 1 ]; then
   echo "Partition already at maximum size - no expansion needed"
   EXPANDED=0
else
   echo "ERROR: growpart failed with code $?"
   exit 1
fi

# If no expansion happened, exit successfully (no reboot needed)
if [ $EXPANDED -eq 0 ]; then
   echo "Filesystem already at maximum size"
   echo "=== No expansion needed - exiting ==="
   exit 0
fi

# Give kernel time to update partition table
echo "Waiting for kernel to update partition table..."
sleep 2
partprobe "$ROOT_DEV" 2>/dev/null || true
sleep 1

# Verify partition was expanded
PART_SIZE_AFTER=$(lsblk -bno SIZE "$ROOT_PART")
echo "New partition size: $(numfmt --to=iec-i --suffix=B $PART_SIZE_AFTER)"

# Resize filesystem based on type
echo "Resizing $FS_TYPE filesystem..."

if [ "$FS_TYPE" = "ext4" ]; then
   # EXT4 resize (SM-140 legacy)
   echo "Running resize2fs on $ROOT_PART..."
   if resize2fs "$ROOT_PART"; then
       echo "EXT4 filesystem resized successfully"
   else
       echo "ERROR: Failed to resize EXT4 filesystem"
       exit 1
   fi
    
elif [ "$FS_TYPE" = "btrfs" ]; then
   # Btrfs resize (SM-170, SM-130, SM-180)
   echo "Running btrfs filesystem resize on /..."
   
   # Check current filesystem size
   FS_SIZE_BEFORE=$(btrfs filesystem usage / 2>/dev/null | grep "Device size:" | awk '{print $3}')
   echo "Current filesystem size: $FS_SIZE_BEFORE"
   
   # Resize to max
   if btrfs filesystem resize max /; then
       echo "Btrfs filesystem resized successfully"
   else
       echo "ERROR: Failed to resize Btrfs filesystem"
       exit 1
   fi
   
   # Show new filesystem size
   sleep 1
   FS_SIZE_AFTER=$(btrfs filesystem usage / 2>/dev/null | grep "Device size:" | awk '{print $3}')
   echo "New filesystem size: $FS_SIZE_AFTER"
fi

echo ""
echo "=== Filesystem expansion complete ==="
echo "System will reboot automatically..."
echo ""

exit 0
