#!/usr/bin/env bash
# OPT-IN: PipeWire/WirePlumber pro-audio routing for the RME Fireface 802.
#
# Creates a stereo null sink ("rme-nullsink") and statically patches it to the
# RME's AES outs (AUX12/13), sets the card to the "pro-audio" profile, and keeps
# the null sink linked to whatever output is active — so Pulse/Wine apps always
# see a stable stereo device. (guide: bennett.dev/auto-link-pipewire-ports-wireplumber)
#
# Hardware-specific: the RME serial is baked into rme-proaudio/auto-connect-ports.lua
# ("Fireface 802 (24240739)") and rme-proaudio/alsa.conf (device.name) — edit those
# for a different unit. Run on the machine with the interface, as your normal user:
#   ./rme-proaudio.sh
set -euo pipefail
[ "$(id -u)" -ne 0 ] || { echo "run as your user, not root (writes ~/.config)"; exit 1; }
cd "$(dirname "$0")"
src=rme-proaudio

PW="$HOME/.config/pipewire/pipewire.conf.d"
WP="$HOME/.config/wireplumber"

install -Dm644 "$src/nullsink.conf"          "$PW/nullsink.conf"
install -Dm644 "$src/auto-connect-ports.lua" "$WP/scripts/auto-connect-ports.lua"
install -Dm644 "$src/alsa.conf"              "$WP/wireplumber.conf.d/alsa.conf"

# The component file registers the lua by ABSOLUTE path (~ isn't expanded here),
# so generate it with $HOME rather than shipping a hardcoded path.
install -Dm644 /dev/stdin "$WP/wireplumber.conf.d/99-auto-connect-ports.conf" <<EOF
wireplumber.components = [
  {
    name = $WP/scripts/auto-connect-ports.lua, type = script/lua
    provides = custom.auto-connect-ports
  }
]

wireplumber.profiles = {
  main = {
    custom.auto-connect-ports = required
  }
}
EOF

echo "RME pro-audio config installed. Restart audio to apply:"
echo "  systemctl --user restart wireplumber pipewire pipewire-pulse"
