FROM golang:1.24-bookworm AS base

RUN apt-get update
run apt-get install -y libssl-dev cmake build-essential gperf libz-dev make git

FROM base AS tdlib

ARG TD_COMMIT
ARG MAKEOPTS
RUN git clone https://github.com/tdlib/td /src/
RUN git -C /src/ checkout "${TD_COMMIT}"
RUN mkdir build
WORKDIR /build/
RUN cmake -DCMAKE_BUILD_TYPE=Release -DCMAKE_INSTALL_PREFIX=/compiled/ /src/
RUN cmake --build . ${MAKEOPTS}
RUN make install

FROM base AS ntgcalls-build
ARG MAKEOPTS
# CMake >= 3.27 required; bookworm ships 3.25
ARG CMAKE_VERSION=3.31.6
RUN curl -fsSL https://github.com/Kitware/CMake/releases/download/v${CMAKE_VERSION}/cmake-${CMAKE_VERSION}-linux-$(uname -m).tar.gz \
    | tar xz -C /usr/local --strip-components=1
RUN apt-get install -y libasound2-dev libpulse-dev
COPY ntgcalls/ /ntgcalls-src/
WORKDIR /ntgcalls-build/
RUN cmake -DCMAKE_BUILD_TYPE=Release \
    -DCMAKE_TOOLCHAIN_FILE=/ntgcalls-src/cmake/Toolchain.cmake \
    -DPython_EXECUTABLE=$(which python3) \
    -DSTATIC_BUILD=ON \
    /ntgcalls-src/
RUN cmake --build . ${MAKEOPTS}

FROM base AS cache
ARG VERSION
COPY --from=tdlib /compiled/ /usr/local/
COPY --from=ntgcalls-build /ntgcalls-src/static-output/lib/libntgcalls.a /usr/local/lib/
COPY --from=ntgcalls-build /ntgcalls-src/static-output/include/ /usr/local/include/
COPY docker/resolv_shim.c /tmp/resolv_shim.c
RUN gcc -c -o /tmp/resolv_shim.o /tmp/resolv_shim.c && \
    ar rcs /usr/local/lib/libresolv_shim.a /tmp/resolv_shim.o
COPY ./ /src
RUN git -C /src checkout "${VERSION}"
RUN git -C /src submodule update --init
WORKDIR /src
RUN go get

FROM cache AS build
ARG MAKEOPTS
ENV CGO_ENABLED=1
ENV CGO_CFLAGS="-I/usr/local/include"
ENV CGO_LDFLAGS="-L/usr/local/lib -lntgcalls -lresolv_shim -lstdc++ -lm -ldl -lrt -lpthread -lz -lresolv"
WORKDIR /src
RUN make ${MAKEOPTS}

FROM scratch AS telegabber
COPY --from=build /src/release/telegabber /usr/local/bin/
ENTRYPOINT ["/usr/local/bin/telegabber"]

FROM scratch AS binaries
COPY --from=telegabber /usr/local/bin/telegabber /
