#!/bin/bash

perform_x86_swapuuid_change() {
# Log file
LOGFILE="/var/log/fix_swap.log"
echo "=== Swap Fix Started: $(date) ===" | tee -a $LOGFILE

# Find the swap partition (e.g., /dev/sda2)
SWAP_PART=$(blkid | grep "swap" | awk -F: '{print $1}')

if [ -z "$SWAP_PART" ]; then
    echo "ERROR: No swap partition found!" | tee -a $LOGFILE
    exit 1
fi

echo "Detected swap partition: $SWAP_PART" | tee -a $LOGFILE

# Disable the swap
sudo swapoff -a
echo "Swap has been disabled." | tee -a $LOGFILE

# Recreate the swap space
sudo mkswap $SWAP_PART
if [ $? -ne 0 ]; then
    echo "ERROR: Failed to recreate the swap space!" | tee -a $LOGFILE
    exit 1
fi

# Retrieve the new UUID
NEW_UUID=$(blkid -s UUID -o value $SWAP_PART)
echo "New UUID: $NEW_UUID" | tee -a $LOGFILE

# Update /etc/fstab with the new UUID
sudo sed -i "s|UUID=[a-f0-9-]\{36\}|UUID=$NEW_UUID|g" /etc/fstab
if [ $? -ne 0 ]; then
    echo "ERROR: Failed to update /etc/fstab!" | tee -a $LOGFILE
    exit 1
fi

echo "/etc/fstab has been successfully updated." | tee -a $LOGFILE

# Enable the swap
sudo swapon -a
if [ $? -ne 0 ]; then
    echo "ERROR: Failed to enable the swap!" | tee -a $LOGFILE
    exit 1
fi

# Check active swap spaces
swapon --show | tee -a $LOGFILE

echo "Swap has been successfully fixed and enabled!" | tee -a $LOGFILE
echo "=== Process Completed: $(date) ===" | tee -a $LOGFILE
}

perform_x86_swapuuid_change
