#!/bin/bash
set -e

FW_NAME="renesas_usb_fw.mem"
FW_PATH="/lib/firmware/$FW_NAME"
USB_LABEL_PATH="/dev/disk/by-partlabel/usb_fw"
MOUNT_POINT="/tmp/usb_fw"
MODULE_MAIN="xhci_pci"
MODULE_RENESAS="xhci_pci_renesas"

if [ -f "$FW_PATH" ]; then
    echo "Firmware already exists at $FW_PATH. Skipping."
    exit 0
fi

mkdir -p "$MOUNT_POINT"

for i in {1..10}; do
    if [ -b "$USB_LABEL_PATH" ]; then
        break
    fi
    echo "Waiting for $USB_LABEL_PATH..."
    sleep 1
done

if mount "$USB_LABEL_PATH" "$MOUNT_POINT"; then
    echo "Mounted $USB_LABEL_PATH at $MOUNT_POINT"

    if [ -f "$MOUNT_POINT/$FW_NAME" ]; then
        echo "Copying firmware..."
        cp -a "$MOUNT_POINT/$FW_NAME" "$FW_PATH"
        echo "Firmware copied to $FW_PATH"

        echo "Unloading USB controller modules..."
        modprobe -r "$MODULE_MAIN" || true
        modprobe -r "$MODULE_RENESAS" || true

        sleep 2

        echo "Reloading USB controller modules..."
        modprobe "$MODULE_RENESAS"
        modprobe "$MODULE_MAIN"

        current_kernel="$(uname -r)"
        echo "Updating initramfs for current kernel: $current_kernel"
        update-initramfs -u -k "$current_kernel"
        echo "Initramfs updated."
    else
        echo "Error: Firmware file '$FW_NAME' not found in USB partition."
        umount "$MOUNT_POINT"
	rmdir "$MOUNT_POINT" || true
        exit 1
    fi

    umount "$MOUNT_POINT"
    rmdir "$MOUNT_POINT" || true
else
    echo "Error: Failed to mount $USB_LABEL_PATH"
    exit 1
fi
