#!/bin/bash -e

CONF_FILE="/boot/extlinux/extlinux.conf"

current_default=$(grep -E "^DEFAULT" "$CONF_FILE" | awk '{print $2}')
echo "Current DEFAULT: $current_default"
echo

echo "Available LABELs:"
i=0
labels=""

for label in $(grep -E "^LABEL" "$CONF_FILE" | awk '{print $2}'); do
    echo "  [$i] $label"
    labels="$labels $label"
    i=$((i+1))
done

echo
read -p "Enter index or label name to set as new DEFAULT (Enter to cancel): " input
[ -z "$input" ] && echo "Cancelled." && exit 0

if echo "$input" | grep -Eq '^[0-9]+$'; then
    i=0
    for label in $labels; do
        if [ "$i" -eq "$input" ]; then
            new_default=$label
            break
        fi
        i=$((i+1))
    done
else
    for label in $labels; do
        if [ "$label" = "$input" ]; then
            new_default=$label
            break
        fi
    done
fi

if [ -z "$new_default" ]; then
    echo "Invalid input!"
    exit 1
fi

echo "Setting DEFAULT to: $new_default"
sudo sed -i "s/^DEFAULT .*/DEFAULT $new_default/" "$CONF_FILE"
