#!/bin/bash
# Maximizer VM audio bridge setup.
# Prepares a QEMU-consumable PulseAudio endpoint fed by the user's
# pipewire-pulse server, so VM guests get a working audio device whose
# "Line In" can be fed from the host (e.g. SonoBus mic output).
#
# What it does (idempotent):
#   1. Enables linger for the target user so systemd --user and
#      pipewire-pulse keep running without an interactive session
#      (without linger, short-lived SSH/VT sessions bounce the user
#      manager every few seconds and kill QEMU's PulseAudio context).
#   2. Adds an extra pipewire-pulse listen address at $VMPULSE_DIR/pulse/native
#      to the user's ~/.config/pipewire/pipewire-pulse.conf.
#   3. Restarts the user's pipewire-pulse so the address exists.
#   4. Creates $VMPULSE_DIR (world-accessible) and syncs the live
#      pid + cookie that QEMU's pa backend needs for discovery/auth.
#
# Run once as root (packaging postinst or gpu-helper). Re-run the sync
# step (SYNC_ONLY=1) before each VM start: pipewire-pulse restarts
# change the pid and can regenerate the cookie.
set -e
VMPULSE_DIR="${VMPULSE_DIR:-/var/tmp/qemurtd}"
TARGET_USER="${TARGET_USER:-${SUDO_USER:-admin129947}}"
RUNTIME_DIR="${RUNTIME_DIR:-/run/user/$(id -u "$TARGET_USER")}"
USER_HOME="${USER_HOME:-$(getent passwd "$TARGET_USER" | cut -d: -f6)}"

mkdir -p "$VMPULSE_DIR/pulse"
chmod 777 "$VMPULSE_DIR" "$VMPULSE_DIR/pulse"

if [ "${SYNC_ONLY:-0}" != "1" ]; then
  # keep the user's systemd instance (and pipewire-pulse) alive without
  # an interactive login session
  loginctl enable-linger "$TARGET_USER" 2>/dev/null || true

  CONF_DIR="$USER_HOME/.config/pipewire"
  CONF="$CONF_DIR/pipewire-pulse.conf"
  mkdir -p "$CONF_DIR"
  [ -f "$CONF" ] || cp /usr/share/pipewire/pipewire-pulse.conf "$CONF"
  if ! grep -q "$VMPULSE_DIR/pulse/native" "$CONF"; then
    python3 - "$CONF" "$VMPULSE_DIR" <<'EOF'
import sys
p, d = sys.argv[1], sys.argv[2]
s = open(p).read()
needle = '        "unix:native"'
add = '        "unix:%s/pulse/native"' % d
if add not in s:
    s = s.replace(needle, needle + "\n" + add, 1)
open(p, "w").write(s)
print("pipewire-pulse.conf: added", add)
EOF
  fi
  # restart the user service (best effort; requires an active user session)
  su - "$TARGET_USER" -c "systemctl --user restart pipewire-pulse.socket pipewire-pulse.service" 2>/dev/null || true
  sleep 2
fi

# sync pid + cookie for QEMU's pa backend discovery/auth
[ -f "$RUNTIME_DIR/pulse/pid" ] && cp "$RUNTIME_DIR/pulse/pid" "$VMPULSE_DIR/pulse/pid" && chmod 644 "$VMPULSE_DIR/pulse/pid"
[ -f "$USER_HOME/.config/pulse/cookie" ] && cp "$USER_HOME/.config/pulse/cookie" "$VMPULSE_DIR/cookie" && chmod 644 "$VMPULSE_DIR/cookie"
mkdir -p /root/.config/pulse
[ -f "$USER_HOME/.config/pulse/cookie" ] && cp "$USER_HOME/.config/pulse/cookie" /root/.config/pulse/cookie

echo "vm-audio-setup done"
