#!/bin/bash

set -e
set -u

# find the root partition information
ROOT_PART="$(mount | sed -n 's|^/dev/\(.*\) on / .*|\1|p')"
ROOT_DEV="/dev/$(lsblk -no pkname /dev/${ROOT_PART})"
PART_NUM="$(echo $ROOT_PART | grep -o "[[:digit:]]*$")"

# Get the starting offset of the root partition
PART_START=$(fdisk -l $ROOT_DEV | grep $ROOT_PART | awk '{print $2}')
[ "$PART_START" ] || return 1 ;

fdisk "$ROOT_DEV" > /dev/null 2>&1 <<EOF
p
d
$PART_NUM
n
p
$PART_NUM
$PART_START

p
w
EOF

resize2fs /dev/$ROOT_PART > /dev/null 2>&1 

echo "Expand rootfs size successfully, it will be enlarged upon the next reboot."

