#!/bin/bash

vg_name=$(vgdisplay | awk '/VG Name/{print $NF}' | head -n 1)
lv_name=$(lvdisplay | awk '/LV Name/{print $NF}' | head -n 1)
file_sys=$(grep -Ev '^$|^#' /etc/fstab | awk '/boot/{print $3}')

ROOT_DEV=$(findmnt -n -o SOURCE /)
[[ $ROOT_DEV == /dev/mapper/* ]] && ROOT_DEV=$(pvs --noheadings -o pv_name | head -1 | xargs)

if [[ $ROOT_DEV =~ ^/dev/(nvme[0-9]+n[0-9]+)p([0-9]+)$ ]] ||
    [[ $ROOT_DEV =~ ^/dev/(mmcblk[0-9]+)p([0-9]+)$ ]]; then
    $(which growpart) /dev/${BASH_REMATCH[1]} ${BASH_REMATCH[2]}
elif [[ $ROOT_DEV =~ ^/dev/([sv]d[a-z]+|xvd[a-z]+)([0-9]+)$ ]]; then
    $(which growpart) /dev/${BASH_REMATCH[1]} ${BASH_REMATCH[2]}
fi

lvextend -l +100%FREE /dev/${vg_name}/${lv_name}

if [ "xfs" = "${file_sys}" ]; then
    xfs_growfs /dev/${vg_name}/${lv_name}
else
    resize2fs /dev/${vg_name}/${lv_name}
fi

rm -f $0

