#!/bin/bash
clear
program=$(basename "$0")
logfile="/var/log/$program.log"

# Function to log messages
log() {
    echo "$(date +'%Y-%m-%d %H:%M:%S') - $1" | tee -a "$logfile"
}

# Function to log variables for debugging
log_variables() {
    echo "--- Debugging Variables ---" >> "$logfile"
    echo "program: $program" >> "$logfile"
    echo "logfile: $logfile" >> "$logfile"
    echo "part: $part" >> "$logfile"
    echo "dev: $dev" >> "$logfile"
    echo "num: $num" >> "$logfile"
    echo "last_part_num: $last_part_num" >> "$logfile"
    echo "--------------------------" >> "$logfile"
}

# Check if the script is run as root
if [[ $(id -u) -ne 0 ]]; then
    log "Error: This script must be run as root (UID 0)."
    exit 1
fi
log "Starting $program"

for cmd in growpart resize2fs; do
    if ! command -v $cmd &> /dev/null; then
        echo "The command '$cmd' is not installed. Please install the necessary package."
        exit 1
    fi
done

# Detect root filesystem partition
part=$(findmnt / -o source -n)
if [ -z "$part" ]; then
    log "Error detecting root filesystem. Exiting."
    exit 1
fi

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

last_part_num=$(parted "$dev" -ms unit s p | tail -n 1 | cut -f 1 -d:)
if [[ "$last_part_num" -ne "$num" ]]; then
    log "Error: $part is not the last partition. Unable to expand."
    exit 2
fi

# Log all variables for debugging
log_variables

# Extend partition
log "Extending partition $num on device $dev to maximum size..."
growpart "$dev" "$num" 2>&1 | tee -a "$logfile" || { log "Error: growpart failed."; exit 3; }

# Resize filesystem
log "Resizing filesystem on $partition..."
resize2fs "$part" 2>&1 | tee -a "$logfile" || { log "Error: resize2fs failed."; exit 4; }

log "Done."
df -h | grep "$part" | tee -a "$logfile"

