FROM rust:1.70-alpine3.18 AS builder

ARG DI_VER=1.2.5

WORKDIR /app

RUN apk add --no-cache \
    build-base \
    curl \
    make \
    unzip \
    pkgconf \
    libarchive libarchive-dev

# Build dumb-init
RUN curl -Lo - "https://github.com/Yelp/dumb-init/archive/refs/tags/v${DI_VER}.tar.gz" | tar -xzf - && \
    cd "dumb-init-${DI_VER}" && \
    make SHELL=/bin/sh && \
    mv dumb-init .. && \
    cd ..

COPY . .

# ENV LIBARCHIVE_STATIC=1 \
#     LIBARCHIVE_LIB_DIR=/usr/lib \
#     LIBARCHIVE_INCLUDE_DIR=/usr/include \
#     LIBARCHIVE_LDFLAGS='-lssl -lcrypto -L/lib -lz -lbz2 -llzma -lexpat -lzstd -llz4'
    # LIBARCHIVE_LDFLAGS='-L/usr/lib -lz -lbz2 -llzma -lexpat -lzstd -llz4 -lsqlite3'

# https://users.rust-lang.org/t/sigsegv-with-program-linked-against-openssl-in-an-alpine-container/52172
ENV RUSTFLAGS='-C target-feature=-crt-static'

RUN cargo build --release && \
    du -h target/release/rieterd && \
    readelf -d target/release/rieterd && \
    chmod +x target/release/rieterd


FROM alpine:3.18

RUN apk add --no-cache \
    libgcc \
    libarchive \
    openssl

COPY --from=builder /app/dumb-init /bin/dumb-init
COPY --from=builder /app/target/release/rieterd /bin/rieterd

ENV RIETER_PKG_DIR=/data/pkgs \
    RIETER_DATA_DIR=/data

WORKDIR /data

ENTRYPOINT ["/bin/dumb-init", "--"]
CMD ["/bin/rieterd"]