ARG BUILD_FROM

# ============================================================
# Build stage: Librespot aus Rust-Quellcode kompilieren
# ============================================================
FROM rust:alpine AS librespot-builder

RUN apk add --no-cache \
    musl-dev \
    pkgconfig \
    openssl-dev \
    openssl-libs-static \
    git

# Librespot auf festem Commit des dev-Branchs (2026-10-21) bauen, patchen und kompilieren.
# Fest gepinnt, weil Umbauten upstream sonst die Patches unbemerkt brechen (passiert im Nov. 2026).
#
# v0.7.0 hat Kompatibilitätsprobleme mit Spotifys aktuellem Backend:
# Spotify liefert keine Audio-Datei-IDs mehr → alle Tracks "not available".
# Der main-Branch enthält Fixes für dieses Problem.
#
# Patches:
# 1. println! → eprintln! für "Browse to:"-URL (stdout geht sonst in ffmpeg-Pipe)
# 2. OAuth-Callback-Server auf 0.0.0.0 binden (statt nur 127.0.0.1)
# 3. Deutsche Erfolgs-Meldung nach OAuth
ARG LIBRESPOT_COMMIT=99b6088bf3ea028f90192676ac1a337fa4b2ed12
RUN git init -q /build && cd /build && \
    git remote add origin https://github.com/librespot-org/librespot.git && \
    git fetch -q --depth 1 origin "${LIBRESPOT_COMMIT}" && git checkout -q FETCH_HEAD && \
    # Patch 1: "Browse to:"-URL auf stderr statt stdout.
    sed -i \
        -e 's/println!("Browse to: /eprintln!("Browse to: /g' \
        -e 's/println!("Provide redirect URL")/eprintln!("Provide redirect URL")/' \
        oauth/src/lib.rs && \
    grep -n "eprintln.*Browse to" oauth/src/lib.rs || { echo "FEHLER: println→eprintln Patch fehlgeschlagen!"; exit 1; } && \
    # Patch 2: OAuth-Callback-Server auf 0.0.0.0 binden (statt nur 127.0.0.1).
    sed -i \
        -e 's/TcpListener::bind(socket_address)/TcpListener::bind(std::net::SocketAddrV4::new(std::net::Ipv4Addr::UNSPECIFIED, socket_address.port()))/' \
        -e 's/Go back to your terminal :)/Autorisierung erfolgreich! Du kannst diesen Tab schliessen./' \
        oauth/src/lib.rs && \
    grep -n "UNSPECIFIED" oauth/src/lib.rs || { echo "FEHLER: TcpListener-Patch fehlgeschlagen!"; exit 1; } && \
    # OpenSSL statisch: das musl-Binary muss auch im Debian-Image laufen (kein musl-libssl dort)
    OPENSSL_STATIC=1 cargo build \
        --release \
        --no-default-features \
        --features "native-tls" && \
    mkdir -p /install/bin && \
    cp target/release/librespot /install/bin/librespot

# ============================================================
# Runtime stage: HA-Basis-Image + ffmpeg + icecast (+ PipeWire für Soloist)
# ============================================================
# amd64/aarch64: Debian (glibc) – Spotify Soloist braucht glibc ≥ 2.38.
# armhf/armv7:   Alpine – für 32-Bit gibt es kein Soloist, dort nur librespot.
# Das librespot-Binary aus dem musl-Build ist statisch gelinkt und läuft auf beiden.
# Soloist selbst steckt NICHT im Image (Spotify erlaubt keine Weitergabe),
# es wird beim Start von Spotify geladen (siehe soloist-fetch.sh).
FROM ${BUILD_FROM}

SHELL ["/bin/bash", "-o", "pipefail", "-c"]

RUN if command -v apk >/dev/null; then \
        apk add --no-cache bash jq curl python3 ffmpeg \
        && { apk add --no-cache --repository=https://dl-cdn.alpinelinux.org/alpine/edge/community icecast \
             || apk add --no-cache icecast; }; \
    else \
        apt-get update \
        && DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends \
            jq curl python3 ffmpeg icecast2 iproute2 procps \
            pipewire pipewire-bin wireplumber libpipewire-0.3-modules libspa-0.2-modules \
            libpulse0 libatomic1 \
        && apt-get clean && rm -rf /var/lib/apt/lists/*; \
    fi

# Librespot-Binary aus dem Build-Stage übernehmen
COPY --from=librespot-builder /install/bin/librespot /usr/local/bin/librespot
RUN chmod +x /usr/local/bin/librespot && librespot --version

# PipeWire im Container: virtuelle Senke, die ffmpeg abgreift (nur Soloist)
ENV XDG_RUNTIME_DIR="/run/pipewire"
COPY pipewire/ /etc/pipewire/pipewire.conf.d/
COPY wireplumber/ /etc/wireplumber/wireplumber.conf.d/

# Add-on Dateien kopieren
COPY run.sh /run.sh
COPY oauth_helper.py /oauth_helper.py
COPY soloist-fetch.sh /usr/local/bin/soloist-fetch
RUN chmod a+x /run.sh /oauth_helper.py /usr/local/bin/soloist-fetch

ARG BUILD_ARCH
ARG BUILD_VERSION
LABEL io.hass.type="addon" io.hass.arch="${BUILD_ARCH}" io.hass.version="${BUILD_VERSION}" \
      io.hass.name="Busch-Radio Spotify Bridge"

CMD ["/run.sh"]
