#!/bin/bash
# udev hotplug handler: attaches a newly plugged block device to a Proxmox VM
# as raw scsi passthrough. Called by a udev rule with the kernel name as $1.

VMID=100                  # target VM id
BOOT_DISK_PATTERN="nvme0" # kernel name of the host boot disk, never attached

KERNEL_NAME="$1"

if echo "$KERNEL_NAME" | grep -q "$BOOT_DISK_PATTERN"; then exit 0; fi

# wait for the device to settle
sleep 3

# resolve stable by-id path
DEVICE_PATH=$(ls -l /dev/disk/by-id/ | grep " ${KERNEL_NAME}$" | awk '{print "/dev/disk/by-id/" $9}' | grep -v part | head -1)

if [ -z "$DEVICE_PATH" ]; then
  logger "disk-passthrough: could not resolve by-id for $KERNEL_NAME, skipping"
  exit 1
fi

# next free scsi slot (scsi0 = OS disk)
NEXT=$(qm config $VMID 2>/dev/null | grep -c "^scsi")

qm set $VMID --scsi${NEXT} "${DEVICE_PATH},format=raw"

logger "disk-passthrough: attached $DEVICE_PATH to VM $VMID as scsi${NEXT}"

# src: ezra, contact: ezkru69@mail.com