# syntax=docker/dockerfile:1
# vi: ft=dockerfile
ARG builder_image
ARG target_image

FROM $builder_image AS builder

# Install build deps
ENV DEBIAN_FRONTEND=noninteractive
RUN apt-get update
RUN apt-get install -y locales git make zlib1g-dev unixodbc-dev gcc g++ libssl-dev curl gpg

# The signing script requires debsigs version 0.2 or higher, which is unavailable in
# package repositories of Ubuntu versions earlier than 24.10 and Debian versions earlier than 13.
# TODO: Remove custom repo setup once older distro support ends.
RUN arch=$(dpkg --print-architecture) && \
    distro=$(grep ^ID= /etc/os-release | cut -d= -f2 | tr -d '"') && \
    if [ "$distro" = "ubuntu" ]; then \
        if [ "$arch" = "arm64" ]; then \
            echo "deb http://ports.ubuntu.com/ubuntu-ports oracular main restricted universe multiverse" >> /etc/apt/sources.list; \
        else \
            echo "deb http://archive.ubuntu.com/ubuntu oracular main restricted universe multiverse" >> /etc/apt/sources.list; \
        fi && \
        printf "Package: debsigs\nPin: release n=oracular\nPin-Priority: 990\n" > /etc/apt/preferences.d/debsigs; \
    elif [ "$distro" = "debian" ]; then \
        echo "deb http://deb.debian.org/debian trixie main" >> /etc/apt/sources.list && \
        printf "Package: debsigs\nPin: release n=trixie\nPin-Priority: 990\n" > /etc/apt/preferences.d/debsigs; \
    fi && \
    apt-get update && \
    apt-get install -y --no-install-recommends debsigs && \
    sed -i '/oracular/d' /etc/apt/sources.list && \
    sed -i '/trixie/d' /etc/apt/sources.list

ARG erlang_version

# Fix locales
RUN locale-gen en_US.UTF-8

# Copy source code and put building files in proper directories
# The .dockerignore file in root dir ensures only needed files
# including not commited changes are used to build the package
WORKDIR /root/
COPY . ./mongooseim

RUN cp -r ./mongooseim/tools/pkg/scripts/deb .

ARG version
ARG revision

RUN ./deb/build_package.sh $version $revision $erlang_version

# Sign the built package with the keys provided
RUN --mount=type=secret,id=GPG_PUBLIC_KEY,env=GPG_PUBLIC_KEY \
    --mount=type=secret,id=GPG_PRIVATE_KEY,env=GPG_PRIVATE_KEY \
    --mount=type=secret,id=GPG_PASS,env=GPG_PASS \
    ./mongooseim/tools/pkg/sign.sh

# Create image for sharing and validation of built package
FROM $target_image AS target

# Copy built package from previous image and install it with required dependencies
ENV DEBIAN_FRONTEND=noninteractive
RUN apt-get update && apt-get -y install openssl procps && apt-get -y clean
WORKDIR /root/
COPY --from=builder /root/*.deb .

# Install mongooseim with required dependencies
RUN apt-get update && dpkg -i *.deb && apt-get install -y -f

# Simple check if MiM works
COPY tools/wait-for-it.sh .
COPY tools/pkg/scripts/smoke_test.sh .
COPY tools/pkg/scripts/smoke_templates.escript .

RUN ./smoke_test.sh

RUN mkdir /built_packages
CMD mv /root/mongooseim*.deb /built_packages
