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 vom aktuellen main-Branch klonen, patchen und kompilieren.
#
# 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
RUN git clone --depth 1 \
        https://github.com/librespot-org/librespot.git /build && \
    cd /build && \
    # Patch 1: "Browse to:"-URL auf stderr statt stdout.
    sed -i \
        -e 's/println!("Browse to: {auth_url}")/eprintln!("Browse to: {auth_url}")/' \
        -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; } && \
    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
# ============================================================
FROM ${BUILD_FROM}

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

# Abhängigkeiten installieren
# icecast liegt in Alpine's Community-Repository
RUN 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

# 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

# Add-on Dateien kopieren
COPY run.sh /run.sh
COPY oauth_helper.py /oauth_helper.py
RUN chmod a+x /run.sh /oauth_helper.py

CMD ["/run.sh"]
