#################################################
FROM debian:bookworm-slim AS builder-base

RUN apt-get update && \
    apt-get install --no-install-recommends -y \
    libpq-dev \
    ca-certificates \
    libc6 \
    libstdc++6 \
    sudo \
    && groupadd --gid 1001 appuser \
    && useradd --uid 1001 --gid appuser --shell /bin/bash --create-home appuser

ENV PYTHONUNBUFFERED=1 \
    PYTHONDONTWRITEBYTECODE=1 \
    UV_VERSION="0.7.6" \
    UV_PYTHON="3.13.3" \
    UV_PYTHON_INSTALL_DIR="/app/.python" \
    UV_PYTHON_PREFERENCE="only-managed" \
    UV_COMPILE_BYTECODE=1 \
    UV_NO_INSTALLER_METADATA=1 \
    UV_LINK_MODE=copy \
    PATH="$PATH:/root/.local/bin/:/app/.venv/bin:/opt/cprocsp/bin/amd64:/opt/cprocsp/sbin/amd64"

# Install CryptoPro CSP 5
WORKDIR /tmp/cryptopro
COPY packages/linux-amd64_deb.tgz /tmp/cryptopro/
RUN tar -xzf linux-amd64_deb.tgz && \
    cd linux-amd64_deb && \
    ./install.sh && \
    dpkg -i cprocsp-cptools-*.deb lsb-cprocsp-base_*.deb lsb-cprocsp-kc1_*.deb lsb-cprocsp-capilite_*.deb || apt-get install -f -y && \
    # Create symbolic links for CryptoPro tools
    ln -s /opt/cprocsp/bin/amd64/certmgr /bin/certmgr && \
    ln -s /opt/cprocsp/bin/amd64/cpverify /bin/cpverify && \
    ln -s /opt/cprocsp/bin/amd64/cryptcp /bin/cryptcp && \
    ln -s /opt/cprocsp/bin/amd64/csptest /bin/csptest && \
    ln -s /opt/cprocsp/sbin/amd64/cpconfig /bin/cpconfig && \
    # Set permissions for CryptoPro directories
    mkdir -p /etc/opt/cprocsp /var/opt/cprocsp && \
    chown -R appuser:appuser /etc/opt/cprocsp /var/opt/cprocsp && \
    # Clean up
    rm -rf /tmp/cryptopro && \
    apt-get clean && \
    rm -rf /var/lib/apt/lists/*

#################################################
FROM builder-base AS python-base

WORKDIR /app

RUN apt-get update && \
    apt-get install --no-install-recommends -y \
    curl \
    clang \
    && curl -LsSf https://github.com/astral-sh/uv/releases/download/${UV_VERSION}/uv-installer.sh | sh && \
    uv python install && \
    apt-get clean && \
    rm -rf /var/lib/apt/lists/*

COPY pyproject.toml ./

RUN uv sync --no-dev -n
RUN uv version --short > .version

#################################################
FROM builder-base AS production

WORKDIR /app

RUN chown -R appuser:appuser /app

COPY --from=python-base /app/.python /app/.python
COPY --from=python-base /app/.venv /app/.venv
COPY --from=python-base /app/.version /app/
COPY /src/ /app/
COPY /scripts/ /app/scripts
RUN chmod -R 755 /app/scripts

USER appuser

CMD ["sh", "./scripts/boot.sh"]
#################################################
