#!/bin/bash
set -e

# Get Disk partition num
PV_NUM=$(lsblk | grep -c "vda")
# Get vg volume name
VG_NAME=$(vgs | awk 'NR!=1 {print $1}')
# Get lv volume name
LV_NAME=$(lvs | awk 'NR!=1{print $1}' | head -1)
# Get disk size
DISK_SIZE=$(lsblk | awk '/^vda/{print $4}')

# Check if disk size is 20G
if [[ "${DISK_SIZE}" == "20G" ]]; then
    exit 0
fi

# Handle script warning exception status codes
function WarningHandler() {
    local command=$1
    set +e
    eval "${command}"
    set -e
}

# Start disk expansion
# Centos Stream 9
if grep -qi 'CentOS Stream 9' /etc/os-release; then
    CentOS_Stream_9

# Centos Stream 8
elif grep -qi 'CentOS Stream 8' /etc/os-release; then
    CentOS_Stream_8

# Centos 7.9
elif grep -qi 'CentOS Linux 7 (Core)' /etc/os-release; then
    CentOS_7.9

# Ubuntu 24.04 TLS
elif grep -qi '24.04' /etc/os-release; then
    Ubuntu_24.04

# Ubuntu 22.04 TLS
elif grep -qi '22.04' /etc/os-release; then
    WarningHandler "echo -e 'n\n\n\n\nw' | fdisk /dev/vda"

# Ubuntu 20.04 TLS
elif grep -qi '20.04' /etc/os-release; then
    WarningHandler "echo -e 'n\n\n\n\nw' | fdisk /dev/vda"

# Ubuntu 18.04 TLS
elif grep -qi '18.04' /etc/os-release; then
    Ubuntu_18.04

# Ubuntu 16.04 TLS
elif grep -qi '16.04' /etc/os-release; then
    WarningHandler "echo -e 'n\np\n\n\n\nw' | fdisk /dev/vda"

else
    echo "Unsupported OS"
    exit 1
fi

while ! lsblk | grep -qi "vda${PV_NUM}"; do
    partprobe /dev/vda
    sleep 1
done

# Create new partition and extend volume group and logical volume
pvcreate /dev/vda${PV_NUM}
vgextend ${VG_NAME} /dev/vda${PV_NUM}
lvextend -l +100%FREE /dev/${VG_NAME}/${LV_NAME}

# Resize filesystem if xfs, otherwise resize2fs
# Note: This script assumes the filesystem is not mounted. If it is, you may need to unmount it first.
File_System=$(grep -Ev '^$|^#' /etc/fstab | awk '/boot/{print $3}')
if [[ "${File_System}" == "xfs" ]]; then
    xfs_growfs /dev/${VG_NAME}/${LV_NAME}
else
    resize2fs /dev/${VG_NAME}/${LV_NAME}
fi
