#!/usr/bin/env bash
# fix-t2-speakers.sh – restore internal speaker output on Apple T2 + KDE/Plasma
#
# Run as your regular KDE user (NOT root).
# -------------------------------------------------------------------------

set -euo pipefail

log() { echo "[+] $*"; }
err() { echo "[!] $*" >&2; }

if [[ "$(id -u)" -eq 0 ]]; then
    err "Run this script as your regular KDE user, not as root."
    exit 1
fi

# 1. Kill anything blocking the T2 device
log "Checking for processes blocking T2 audio..."
BLOCKED=0
for pid in $(fuser /dev/snd/pcmC0D0p /dev/snd/controlC0 2>/dev/null | tr -d ' ' | tr -s ' ' '\n' | sort -u); do
    if [[ -n "$pid" ]] && [[ "$pid" != "PID" ]]; then
        CMD=$(ps -p "$pid" -o cmd= 2>/dev/null | head -c 80)
        log "  Killing: PID $pid ($CMD)"
        kill "$pid" 2>/dev/null || true
        BLOCKED=1
    fi
done
pgrep -x fluidsynth >/dev/null 2>&1 && { killall fluidsynth 2>/dev/null || true; BLOCKED=1; }
systemctl --user is-active --quiet fluidsynth 2>/dev/null && { systemctl --user stop fluidsynth 2>/dev/null; systemctl --user disable fluidsynth 2>/dev/null; BLOCKED=1; }
[[ "$BLOCKED" -eq 1 ]] && { log "  Waiting for device release..."; sleep 2; }

# 2. Restart PipeWire
log "Restarting PipeWire/PulseAudio..."
systemctl --user restart pipewire pipewire-pulse
sleep 2
pactl info >/dev/null 2>&1 || { err "Cannot contact PipeWire."; exit 1; }

# 3. Wait for T2 card
CARD="alsa_card.pci-0000_e6_00.3"
for i in $(seq 1 20); do
    pactl list cards short 2>/dev/null | grep -q "$CARD" && break
    sleep 0.5
done
pactl list cards short 2>/dev/null | grep -q "$CARD" || { err "T2 card not visible."; exit 1; }
log "T2 card detected."

# 4. Default profile
pactl set-card-profile "$CARD" Default 2>/dev/null || true
sleep 1

# 5. Find and select Speakers sink
SINK="alsa_output.pci-0000_e6_00.3.Speakers"
pactl list sinks short 2>/dev/null | grep -q "$SINK" || SINK=$(pactl list sinks | awk '/Name:/ {n=$2} /alsa.card = "0"/ {print n; exit}')
[[ -z "$SINK" ]] && { err "No T2 sink found."; exit 1; }
log "Sink: $SINK"

pactl set-default-sink "$SINK"
pactl set-sink-mute "$SINK" 0
pactl set-sink-volume "$SINK" 65%

# 6. Test
log "Playing test tone (~2 sec)..."
speaker-test -D pipewire -c 2 -l 1 &
sleep 3
kill $! 2>/dev/null || true

log "Done! If you heard the tone, your speakers work."
log "Prevent recurrence: systemctl --user disable --now fluidsynth"