#!/usr/bin/env bash
#
# Unplug all framegrabbers (remove xdma devices).

# Enable unofficial bash strict mode.
set -euo pipefail
IFS=$'\n\t'

# Check root permissions.
if [[ "$EUID" -ne 0 ]]; then
  echo "Please run with sudo" >&2
  exit 1
fi

# Get xdma drivers/cards to unplug.
# Exit successfully if nothing to unplug.
cards="$(find -L /sys/bus/pci/drivers/xdma/* -maxdepth 1 -name "remove")"
if [[ -z "${cards}" ]]; then
  echo "Already unplugged."
  exit 0
fi

# Check motherboard.
board="$(cat /sys/class/dmi/id/board_name)"
if [[ "${board}" != "X11DPG-QT" && "${1:-}" != "--force" ]]; then
  echo "Unsupported motherboard: Hot swapping may damage hardware (use --force to override)" >&2
  exit 1
fi

# Show each xdma driver/card being unplugged.
echo "Detected '${board}', attempting to remove xdma."
for card in $cards; do
  echo "Unplugging: ${card}"
  echo 1 > "${card}"
done

# Show any Xilinx devices that were not unplugged.
if plugged="$(lspci | grep Xilinx)"; then
  echo "Could not unplug:" >&2
  echo "${plugged}" >&2
  exit 1
fi
