# =========
#  Builder
# =========
FROM rust:bookworm as builder
WORKDIR /builder

COPY migrations ./migrations
COPY src ./src
COPY Cargo.toml ./

RUN apt-get update && apt-get install -y cmake
RUN cargo build --release

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

ARG TARGETPLATFORM

RUN apt-get update && apt-get install -y curl tar xz-utils && \
  if [ "$TARGETPLATFORM" = "linux/amd64" ]; then \
    echo "Unsupported platform: amd64" && false; \
  elif [ "$TARGETPLATFORM" = "linux/arm/v7" ]; then \
    curl -L https://github.com/yt-dlp/yt-dlp/releases/latest/download/yt-dlp_linux_armv7l > yt-dlp && \
    chmod +x yt-dlp; \
  elif [ "$TARGETPLATFORM" = "linux/aarch64" ]; then \
    curl -L https://github.com/yt-dlp/yt-dlp/releases/latest/download/yt-dlp_linux_aarch64 > yt-dlp && \
    chmod +x yt-dlp; \
  elif [ "$TARGETPLATFORM" = "linux/arm64" ]; then \
    curl -L https://github.com/yt-dlp/yt-dlp/releases/latest/download/yt-dlp_linux_aarch64 > yt-dlp && \
    chmod +x yt-dlp && \
    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" ]; then \
    curl -L https://github.com/yt-dlp/yt-dlp/releases/latest/download/yt-dlp_linux > yt-dlp && \
    chmod +x yt-dlp && \
    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; \
  else \
    echo "Unsupported platform: $TARGETPLATFORM" && false; \
fi

# =========
#  Runtime
# =========
FROM debian:bookworm-slim as runtime
WORKDIR /service
USER root

COPY --from=builder /builder/target/release/service /usr/local/bin/service
COPY --from=packages /packages /usr/bin

RUN apt-get update && apt-get install -y libc6 libc6-dev libopus-dev libpq5 libpq-dev python3-pip ffmpeg

CMD ["service"]
