# Stage 1: Build
FROM --platform=$BUILDPLATFORM ubuntu:22.04 AS builder

ARG BUILDPLATFORM
ARG TARGETPLATFORM
ARG TARGETARCH

ENV DEBIAN_FRONTEND=noninteractive

# Install build dependencies
RUN apt-get update && apt-get install -y \
    qtbase5-dev \
    qtchooser \
    qt5-qmake \
    qtbase5-dev-tools \
    wget \
    git \
    build-essential \
    libqt5core5a \
    && rm -rf /var/lib/apt/lists/*

# Download appropriate 3proxy binary based on architecture
RUN if [ "$TARGETARCH" = "amd64" ]; then \
    wget -O 3proxy.deb https://github.com/3proxy/3proxy/releases/download/0.9.4/3proxy-0.9.4.x86_64.deb; \
    elif [ "$TARGETARCH" = "arm64" ]; then \
    wget -O 3proxy.deb https://github.com/3proxy/3proxy/releases/download/0.9.4/3proxy-0.9.4.aarch64.deb || \
    { echo "ARM64 binary not available, using x86_64"; wget -O 3proxy.deb https://github.com/3proxy/3proxy/releases/download/0.9.4/3proxy-0.9.4.x86_64.deb; }; \
    elif [ "$TARGETARCH" = "arm" ]; then \
    wget -O 3proxy.deb https://github.com/3proxy/3proxy/releases/download/0.9.4/3proxy-0.9.4.armv7l.deb || \
    { echo "ARMv7 binary not available"; exit 1; }; \
    fi && \
    dpkg -i 3proxy.deb || true

# Build 3proxy-eagle in a dedicated source directory
RUN git clone https://gitea.darkness.services/acetone/3proxy-eagle.git /src/3proxy-eagle \
    && cd /src/3proxy-eagle \
    && find . -name "*.cpp" -o -name "*.h" | xargs sed -i 's/127\.0\.0\.1/0.0.0.0/g' \
    && cd /src/3proxy-eagle/src \
    && qmake 3proxy-eagle.pro \
    && make -j$(nproc)

# Stage 2: Runtime
FROM ubuntu:22.04

ARG TARGETARCH

RUN apt-get update && apt-get install -y \
    libqt5core5a \
    libqt5network5 \
    libqt5xml5 \
    libqt5sql5 \
    libqt5sql5-sqlite \
    ca-certificates \
    && rm -rf /var/lib/apt/lists/*

# Copy binaries using the correct absolute paths from Stage 1
COPY --from=builder /usr/bin/3proxy /usr/bin/3proxy
COPY --from=builder /src/3proxy-eagle/src/3proxy-eagle /usr/bin/3proxy-eagle

# Setup config directories
RUN mkdir -p /etc/3proxy /etc/3proxy-eagle/data

# Ensure these files exist in your local directory where you run 'docker build'
#COPY first-instanse.cfg /etc/3proxy/
#COPY second-instanse.cfg /etc/3proxy/

EXPOSE 8161

# Run in foreground
CMD ["/usr/bin/3proxy-eagle", \
     "-i", "/usr/bin/3proxy,/etc/3proxy/first-instanse.cfg", \
     "-i", "/usr/bin/3proxy,/etc/3proxy/second-instanse.cfg", \
     "-w", "/etc/3proxy-eagle/data", \
     "-t", "DarkProxy"]
