# syntax=docker/dockerfile:1

# =========
#  Builder
# =========
FROM rust:1.87-slim-bookworm AS builder
WORKDIR /app
COPY . .
RUN --mount=type=cache,target=/usr/local/cargo/registry,sharing=locked \
    --mount=type=cache,target=/usr/local/cargo/git,sharing=locked \
    --mount=type=cache,target=/app/target,sharing=locked \
    cargo build --release --bin siren && \
    cp /app/target/release/siren /siren

# ==========
#  Packages
# ==========
FROM debian:bookworm-slim AS packages
WORKDIR /packages

ARG TARGETPLATFORM

RUN apt-get update && apt-get install -y python3 curl tar xz-utils && \
  # Download the platform-independent yt-dlp binary
  curl -L https://github.com/yt-dlp/yt-dlp/releases/latest/download/yt-dlp > yt-dlp && \
  # Make yt-dlp executable
  chmod +x yt-dlp && \
  # Install ffmpeg for media conversions
  if [ "$TARGETPLATFORM" = "linux/arm64" ]; then \
    curl -L https://github.com/yt-dlp/FFmpeg-Builds/releases/download/latest/ffmpeg-master-latest-linuxarm64-gpl.tar.xz > ffmpeg.tar.xz && \
    tar -xJf ffmpeg.tar.xz --wildcards */bin/ffmpeg --transform='s/^.*\///' && rm ffmpeg.tar.xz; \
  elif [ "$TARGETPLATFORM" = "linux/x86_64" ] || [ "$TARGETPLATFORM" = "linux/amd64" ]; then \
    curl -L https://github.com/yt-dlp/FFmpeg-Builds/releases/download/latest/ffmpeg-master-latest-linux64-gpl.tar.xz > ffmpeg.tar.xz && \
    tar -xJf ffmpeg.tar.xz --wildcards */bin/ffmpeg --transform='s/^.*\///' && rm ffmpeg.tar.xz; \
  fi

# =========
#  Runtime
# =========
FROM debian:bookworm-slim AS runtime
WORKDIR /siren
USER root

COPY --from=builder /siren /usr/local/bin/siren
COPY --from=packages /packages/yt-dlp /usr/bin/yt-dlp
COPY --from=packages /packages/ffmpeg /usr/bin/ffmpeg

RUN apt-get update && apt-get install -y --no-install-recommends \
    libc6 \
    libc6-dev \
    libopus-dev \
    libpq5 \
    libpq-dev \
    python3-pip \
    && rm -rf /var/lib/apt/lists/*

CMD ["siren"]
