#!/bin/bash

remove_usb() {
    local usb_device
    local attempt=0
    local max_attempts=6
    local delay=0.5

    while [ $attempt -lt $max_attempts ]; do
        usb_device=$(blkid | grep UTOSBOOT | cut -d: -f1)
        if [ -n "$usb_device" ]; then
            for usb_device_path in $usb_device; do
                usb_device=$(basename "$usb_device_path")
                usb_device="${usb_device//[0-9]}"

                echo 0 >/sys/block/$usb_device/device/delete
                if [ $? -eq 0 ];then
                    echo "USB device ($usb_device) with label UTOSBOOT was removed after $attempt attempts." | tee -a /tmp/umount_BOOTUSB.log
                else
                    echo "USB device ($usb_device) with label UTOSBOOT was failed to remove after $attempt attempts." | tee -a /tmp/umount_BOOTUSB.log
                fi
            done
            exit 0
        fi
        attempt=$((attempt + 1))
        sleep $delay
    done

    echo "USB device with label UTOSBOOT not found after $max_attempts attempts." | tee -a /tmp/umount_BOOTUSB.log
    exit 1
}

remove_usb
