#!/bin/bash

# Check if the script is run with sudo
if [[ $EUID -ne 0 ]]; then
    echo "This script needs to be run with sudo to access blkid information."
    echo "Usage: sudo ./create_fstab.sh"
    exit 1
fi


# Get blkid output
BLKID_OUTPUT=$(sudo blkid)

# Temporary file for fstab
TMP_FSTAB=$(mktemp)

# Process each line from blkid
echo "$BLKID_OUTPUT" | while IFS= read -r line; do
    DEVICE=$(echo "$line" | awk -F: '{print $1}')

    # Extract UUID, TYPE, and LABEL (safely)
    UUID=$(echo "$line" | grep -oP 'UUID="\K[^"]+' | head -n1)
    TYPE=$(echo "$line" | grep -oP 'TYPE="\K[^"]+' | tail -n1)
    LABEL=$(echo "$line" | grep -oP 'LABEL="\K[^"]+' | head -n1)

    if [[ -n "$UUID" && -n "$TYPE" ]]; then
        if [[ "$TYPE" == "ext4" ]]; then
            echo -e "UUID=$UUID\t/\text4\trw,relatime\t0\t1" >> "$TMP_FSTAB"
        elif [[ "$TYPE" == "vfat" && "$LABEL" == "BOOT" ]]; then
            echo -e "UUID=$UUID\t/media/caninos/BOOT\tvfat\tdefaults\t0\t0" >> "$TMP_FSTAB"
        else
            echo "  No specific fstab rule for this type/label combination. (Type: $TYPE, Label: $LABEL)"
        fi
    else
        echo "  UUID or TYPE not found for this line. Skipping. (UUID: '$UUID', Type: '$TYPE')"
    fi
done

# Add tracefs line
echo -e "tracefs\t/sys/kernel/tracing\ttracefs\trw,nosuid,nodev,noexec\t0\t0" >> "$TMP_FSTAB"


# Save result
mv "$TMP_FSTAB" fstab

echo "fstab file created successfully:"
cat fstab

