#!/bin/bash

# =========================
# Functions
# =========================
clear
apt update && apt install -y sudo curl wget e2fsprogs hdparm
rm find_fix_bad_sectors.sh
clear
# Function to list non-NVMe drives and let user choose
select_drive() {
    echo "Available drives (excluding NVMe):"

    # List all /dev/sdX devices with model and size, excluding partitions
    mapfile -t DRIVES < <(lsblk -d -o NAME,TYPE | awk '$2=="disk" && $1!~/^nvme/ {print $1}')

    if [ ${#DRIVES[@]} -eq 0 ]; then
        echo "No compatible drives found (non-NVMe)."
        exit 1
    fi

    # Display numbered list
    for i in "${!DRIVES[@]}"; do
        DEV="/dev/${DRIVES[$i]}"
        SIZE=$(lsblk -d -n -o SIZE "$DEV")
        MODEL=$(lsblk -d -n -o MODEL "$DEV")
        echo "$((i+1)). ${DRIVES[$i]}  ($SIZE, $MODEL)"
    done

    # Get user choice
    while true; do
        read -p "Select a drive number: " CHOICE
        if [[ "$CHOICE" =~ ^[0-9]+$ ]] && [ "$CHOICE" -ge 1 ] && [ "$CHOICE" -le ${#DRIVES[@]} ]; then
            DEVICE="/dev/${DRIVES[$((CHOICE-1))]}"
            echo "Selected device: $DEVICE"
            break
        else
            echo "Invalid choice. Please select a valid number."
        fi
    done
}

# Function to run badblocks and store results
run_badblocks() {
    echo "Running badblocks on $DEVICE..."
    sudo badblocks -sv "$DEVICE" > badsectors.txt
}

# Function to process bad sectors with hdparm
repair_bad_sectors() {
    if [ -s badsectors.txt ]; then
        echo "Bad sectors found, running hdparm..."
        while read -r sector; do
            if [[ "$sector" =~ ^[0-9]+$ ]]; then
                sudo hdparm --write-sector "$sector" --yes-i-know-what-i-am-doing "$DEVICE"
            fi
        done < badsectors.txt
    else
        echo "No bad sectors found."
        exit 0
    fi
}

# =========================
# Main Script Flow
# =========================
select_drive
run_badblocks
repair_bad_sectors
