#!/usr/bin/env bash
# install-multimedia-codecs.sh
# Void Linux: Repos absichern (nonfree/multilib) + Multimedia-Codecs/Player
# + Browser-Helfer + optional Flatpak/Flathub + ffmpeg-full (für Flatpak).
# Hinweis: PipeWire wurde komplett entfernt (weder Pakete noch Services).

set -euo pipefail

# ------------------------------ Farben ------------------------------
GREEN="\033[1;32m"; YELLOW="\033[1;33m"; RED="\033[1;31m"; CYAN="\033[1;36m"; RESET="\033[0m"
msg() { echo -e "${CYAN}==>${RESET} $*"; }
ok()  { echo -e "${GREEN}✓${RESET} $*"; }
warn(){ echo -e "${YELLOW}!${RESET} $*"; }
err() { echo -e "${RED}✗${RESET} $*"; }

# -------------------------- Paketlisten (XBPS) -----------------------
# Kern (FFmpeg + GStreamer + Player)
XBPS_CORE_PKGS=(
  ffmpeg ffmpegthumbnailer
  gstreamer1 gst-libav
  gst-plugins-base1 gst-plugins-good1 gst-plugins-bad1 gst-plugins-ugly1
  gstreamer-vaapi
  libdvdcss libdvdread libdvdnav
  libva-utils
  alsa-utils                # Audio-Basis
)

# Proprietäre/zusätzliche Codecs für Web & Transcoding
XBPS_EXTRA_CODECS=(
  x264 x265
  lame faac faad2
  libmad libmpg123
  chromium-widevine         # DRM/Widevine für Chromium-basierte Browser
)

# -------------------------- Flatpak Runtimes -------------------------
# ffmpeg-full für Freedesktop/KDE Plattformen (versucht mehrere Branches)
FLATPAK_RUNTIMES=(
  "org.freedesktop.Platform//24.08"
  "org.freedesktop.Platform.ffmpeg-full//24.08"
  "org.kde.Platform//6.7"
  "org.kde.Platform.ffmpeg-full//6.7"
  "org.freedesktop.Platform//23.08"
  "org.freedesktop.Platform.ffmpeg-full//23.08"
)

# ---------------------------- Helpers -------------------------------
require_root() {
  if [ "$(id -u)" -ne 0 ]; then
    echo -e "${RED}Bitte mit Root-Rechten ausführen (sudo).${RESET}"; exit 1
  fi
}

xbps_pkg_in_repos() {
  xbps-query -Rs "^$1(-|$)" >/dev/null 2>&1
}

ensure_file_with_line() {
  local file="$1" line="$2"
  mkdir -p "$(dirname "$file")"
  if [ -f "$file" ] && grep -qE "^\s*repository\s*=\s*${line}\s*$" "$file"; then
    return 0
  fi
  printf "repository=%s\n" "$line" > "$file"
}

# ------------------------- Repositories setzen ----------------------
ensure_void_repos() {
  msg "Repos prüfen/setzen …"
  local arch subdir base url_main url_nonfree url_multilib url_multilib_nonfree
  arch="$(xbps-uhelper arch)"
  base="https://repo-default.voidlinux.org"

  if [[ "$arch" == *-musl ]]; then
    subdir="current/musl"
  else
    subdir="current"
  fi

  url_main="${base}/${subdir}"
  url_nonfree="${base}/${subdir}/nonfree"
  url_multilib="${base}/current/multilib"
  url_multilib_nonfree="${base}/current/multilib/nonfree"

  ensure_file_with_line "/etc/xbps.d/00-repository-main.conf"         "$url_main";            ok "Main:        $url_main"
  ensure_file_with_line "/etc/xbps.d/10-repository-nonfree.conf"      "$url_nonfree";         ok "Nonfree:     $url_nonfree"

  if [[ "$arch" == "x86_64" ]]; then
    ensure_file_with_line "/etc/xbps.d/10-repository-multilib.conf"         "$url_multilib";        ok "Multilib:    $url_multilib"
    ensure_file_with_line "/etc/xbps.d/10-repository-multilib-nonfree.conf" "$url_multilib_nonfree"; ok "ML Nonfree:  $url_multilib_nonfree"
  else
    warn "Multilib wird für Architektur '${arch}' übersprungen."
  fi

  msg "Repository-Index aktualisieren …"
  xbps-install -S
  ok "Repos aktualisiert."
}

# --------------------- Installation (XBPS) --------------------------
install_pkg_list() {
  local title="$1"; shift
  local pkgs=("$@")
  msg "$title"
  local to_install=()
  for p in "${pkgs[@]}"; do
    if xbps_pkg_in_repos "$p"; then
      echo -e "  ${GREEN}+${RESET} $p"
      to_install+=("$p")
    else
      echo -e "  ${YELLOW}-${RESET} $p (nicht in Repos gefunden)"
    fi
  done
  if ((${#to_install[@]}==0)); then
    warn "Keine passenden Pakete für: $title"
    return 0
  fi
  xbps-install -y "${to_install[@]}"
}

install_xbps_multimedia() {
  msg "System aktualisieren (xbps-install -Syu) …"
  xbps-install -Syu
  install_pkg_list "Multimedia-Basis (FFmpeg/GStreamer/Player/DVD) installieren …" "${XBPS_CORE_PKGS[@]}"
  install_pkg_list "Zusätzliche Codecs für Web (H.264/H.265/AAC/MP3) & Widevine …" "${XBPS_EXTRA_CODECS[@]}"
  ok "XBPS-Multimedia-Installation abgeschlossen."
}

# ------------------------- Browser-Helfer ---------------------------
browser_helpers() {
  msg "Browser-Helfer …"
  if command -v firefox >/dev/null 2>&1; then
    ok "Firefox gefunden. Hinweis:"
    cat <<'EOF'
  - In Firefox (about:config) prüfen/setzen:
      media.ffmpeg.enabled = true
      media.ffvpx.enabled  = false   (optional, damit System-FFmpeg genutzt wird)
      media.ffmpeg.vaapi.enabled = true (optional für VAAPI)
  - Danach Firefox neu starten.
EOF
  fi

  if command -v chromium >/dev/null 2>&1 || command -v brave >/dev/null 2>&1 || command -v vivaldi >/dev/null 2>&1; then
    ok "Chromium/Chromium-basierter Browser gefunden. Hinweise:"
    cat <<'EOF'
  - Paket "chromium-widevine" (nonfree) stellt Widevine/DRM bereit (Netflix/Prime).
  - libffmpeg (aus ffmpeg-libs) liefert H.264/H.265 für HTML5-Video.
  - Browser neu starten.
EOF
  fi
}

# ------------------------- Flatpak/Flathub -------------------------
ensure_flatpak_and_flathub() {
  msg "Flatpak/Flathub einrichten …"
  if ! command -v flatpak >/dev/null 2>&1; then
    msg "Flatpak nicht installiert – Installation via XBPS …"
    if xbps_pkg_in_repos "flatpak"; then
      xbps-install -y flatpak
      ok "Flatpak installiert."
    else
      warn "Flatpak nicht in Repos – überspringe Flatpak-Teil."
      return 0
    fi
  else
  ok "Flatpak bereits vorhanden."
  fi

  flatpak remote-add --if-not-exists flathub https://flathub.org/repo/flathub.flatpakrepo || true
  ok "Flathub konfiguriert."
}

install_flatpak_codecs() {
  msg "Flatpak-Plattformen & ffmpeg-full installieren (sofern verfügbar) …"
  local any_ok=0
  for rt in "${FLATPAK_RUNTIMES[@]}"; do
    if flatpak install -y flathub "$rt"; then
      ok "Installiert: $rt"; any_ok=1
    else
      echo -e "  ${YELLOW}… nicht verfügbar:${RESET} $rt"
    fi
  done
  if [[ "$any_ok" -eq 0 ]]; then
    warn "Keine der vorgegebenen Flatpak-Runtimes verfügbar. Falls nötig, Branches anpassen (z. B. 24.08/23.08/6.8)."
  else
    ok "Flatpak-Codecs/Plattformen eingerichtet."
  fi
}

# ---------------------------------- MAIN ------------------------------------
main() {
  require_root
  echo -e "${CYAN}== Void Linux Multimedia Codecs Setup ==${RESET}"

  ensure_void_repos
  install_xbps_multimedia
  browser_helpers

  echo
  read -r -p "Flatpak + Flathub + ffmpeg-full für Flatpak einrichten? [J/n] " yn
  yn=${yn:-J}
  if [[ "$yn" =~ ^[JjYy] ]]; then
    ensure_flatpak_and_flathub
    install_flatpak_codecs
  else
    warn "Flatpak-Teil übersprungen."
  fi

  echo
  ok "Fertig."
  echo "Hinweise:"
  echo "- Browser neu starten und Videotests prüfen (H.264/H.265)."
  echo "- Für Systeme ohne nonfree: libdvdcss/DRM/HEVC können fehlen."
}

main "$@"

