dotfiles/.config/scripts/libvirt/attach-usb

55 lines
1.4 KiB
Bash
Executable File

#!/bin/bash
script_location="$(readlink -f "$0")"
cd "$(dirname $script_location)"
menu() {
if [ -z "$DISPLAY" ]; then
echo -e "$1" | fzf --prompt="$2"
return 0
fi
echo -e "$1" | menucmd -p "$2"
}
csv="$(virsh list | tail --line=+3 | tr ' ' '\n' | uniq | grep -v -e "^[[:space:]]*$" | tr '\n' ',')"
vms="$(echo "$csv" | awk -F ',' -v n='3' '{
for (i = 1; i+1 <= NF; i++) {
printf "%s ", $i
if (i % n == 0) {
printf "\n"
}
}
}')"
if [ -z "$vms" ]; then
menu "No VMs running" "Error"
exit 1
fi
vm="$(menu "$vms" "VM")"
vm_name=$(echo "$vm" | awk '{print $2}')
directory="./usb-devices"
item_list=""
for file in "$directory"/*; do
item_list="${item_list}$(basename $file)\n"
done
# strip last newline
end=${#item_list}-2
item_list=${item_list:0:end}
device="${directory}/$(menu "$item_list" "Device")"
[ -z "$device" ] && exit 1
output=$(virsh attach-device "$vm_name" "$device" 2>&1) && echo "Attached $device to $vm_name"
if [ $? -ne 0 ]; then
virsh detach-device "$vm_name" "$device" &> /dev/null && echo "Detached $device from $vm_name"
if [ $? -ne 0 ]; then
attached_vm_name="$(echo "$output" | grep domain | rev | awk '{print $1}' | rev)"
virsh detach-device "$attached_vm_name" "$device" &> /dev/null && echo "Detached $device from $attached_vm_name"
virsh attach-device "$vm_name" "$device" &> /dev/null && echo "Attached $device to $vm_name"
fi
fi