#!/usr/bin/env bash
set -euo pipefail

# PipeWire + WirePlumber + pipewire-pulse setup for Void Linux
# - installs packages
# - removes pulseaudio if present
# - creates Void-documented config fragment symlinks:
#     10-wireplumber.conf and 20-pipewire-pulse.conf
# - enables user autostart via runit user service (pipewire only)

# Usage:
#   sudo ./install-pipewire-void.sh            # system-wide config (default)
#   sudo MODE=user ./install-pipewire-void.sh  # per-user config for the invoking user

MODE="${MODE:-system}"  # "system" or "user"

if [[ "${EUID}" -ne 0 ]]; then
  echo "Bitte als root ausführen (z.B. sudo $0)."
  exit 1
fi

USER_NAME="${SUDO_USER:-}"
if [[ -z "${USER_NAME}" || "${USER_NAME}" == "root" ]]; then
  echo "Konnte den Ziel-User nicht bestimmen (SUDO_USER leer). Starte mit sudo als normaler User."
  exit 1
fi

USER_HOME="$(getent passwd "$USER_NAME" | cut -d: -f6)"
if [[ -z "${USER_HOME}" || ! -d "${USER_HOME}" ]]; then
  echo "Konnte Home-Verzeichnis für ${USER_NAME} nicht finden."
  exit 1
fi

echo "==> Ziel-User: ${USER_NAME}"
echo "==> MODE:      ${MODE}"

echo "==> Installiere Pakete"
xbps-install -Sy pipewire wireplumber pipewire-pulse \
  alsa-utils alsa-plugins-pulseaudio \
  libspa-bluetooth \
  pavucontrol

echo "==> Entferne PulseAudio, falls installiert"
if xbps-query -p pkgver pulseaudio >/dev/null 2>&1; then
  xbps-remove -Ry pulseaudio || true
fi

# --- Create config fragment symlinks as per Void docs ---
link_conf() {
  local target="$1"
  local linkpath="$2"

  if [[ -e "$linkpath" || -L "$linkpath" ]]; then
    # If it's already correct symlink, keep; otherwise replace.
    if [[ -L "$linkpath" && "$(readlink -f "$linkpath")" == "$(readlink -f "$target")" ]]; then
      echo "   -> OK: $linkpath"
      return 0
    fi
    echo "   -> Ersetze: $linkpath"
    rm -f "$linkpath"
  fi

  ln -s "$target" "$linkpath"
  echo "   -> Link: $linkpath -> $target"
}

if [[ "$MODE" == "system" ]]; then
  echo "==> Systemweite PipeWire-Konfiguration (Void-Doku) anlegen"
  install -d -m 0755 /etc/pipewire/pipewire.conf.d

  link_conf /usr/share/examples/wireplumber/10-wireplumber.conf \
            /etc/pipewire/pipewire.conf.d/10-wireplumber.conf

  link_conf /usr/share/examples/pipewire/20-pipewire-pulse.conf \
            /etc/pipewire/pipewire.conf.d/20-pipewire-pulse.conf

elif [[ "$MODE" == "user" ]]; then
  echo "==> Per-User PipeWire-Konfiguration (Void-Doku) anlegen"
  XDG_CONFIG_HOME="${XDG_CONFIG_HOME:-${USER_HOME}/.config}"
  USER_PIPEWIRE_DIR="${XDG_CONFIG_HOME}/pipewire/pipewire.conf.d"

  install -d -m 0755 -o "$USER_NAME" -g "$USER_NAME" "$USER_PIPEWIRE_DIR"

  link_conf /usr/share/examples/wireplumber/10-wireplumber.conf \
            "${USER_PIPEWIRE_DIR}/10-wireplumber.conf"

  link_conf /usr/share/examples/pipewire/20-pipewire-pulse.conf \
            "${USER_PIPEWIRE_DIR}/20-pipewire-pulse.conf"

  chown -h "$USER_NAME:$USER_NAME" \
    "${USER_PIPEWIRE_DIR}/10-wireplumber.conf" \
    "${USER_PIPEWIRE_DIR}/20-pipewire-pulse.conf"
else
  echo "ERROR: MODE muss 'system' oder 'user' sein."
  exit 1
fi

echo "==> Stelle sicher, dass der User in der 'audio' Gruppe ist"
usermod -aG audio "${USER_NAME}" || true

# --- Autostart via runit user services ---
# With the above config fragments, pipewire should spawn WirePlumber and pipewire-pulse itself.
echo "==> User-runit Autostart einrichten (pipewire)"
USER_RUNIT_DIR="${USER_HOME}/.config/runit/sv"
install -d -m 0755 -o "${USER_NAME}" -g "${USER_NAME}" "${USER_RUNIT_DIR}"

if [[ -d "/etc/sv/pipewire" ]]; then
  if [[ -L "${USER_RUNIT_DIR}/pipewire" ]]; then
    echo "   -> pipewire ist bereits verlinkt."
  else
    ln -s "/etc/sv/pipewire" "${USER_RUNIT_DIR}/pipewire"
    chown -h "${USER_NAME}:${USER_NAME}" "${USER_RUNIT_DIR}/pipewire"
    echo "   -> pipewire verlinkt."
  fi
else
  echo "WARN: /etc/sv/pipewire nicht gefunden. (Service-Name/Paket prüfen)"
fi

echo
echo "==> Fertig."
echo "Wichtig: Bitte ab- und wieder anmelden (oder reboot)."
echo
echo "Checks:"
echo "  - PipeWire läuft?:   pw-cli info 0 >/dev/null 2>&1 && echo OK || echo FAIL"
echo "  - Pulse-Interface?:  pactl info | grep -E 'Server Name|Server String' || true"
echo "  - Mixer:             pavucontrol"
