# =============================================================================
# Dockerfile — Construction multi-stage du démon ja4ebpf
# Stage 1 : compilation eBPF (Rocky Linux 9 + clang + bpftool)
# Stage 2 : compilation Go + génération des bindings bpf2go
# Stage 3 : image finale minimale (Rocky Linux 9 minimal)
# =============================================================================

# --- Stage 1 : eBPF builder ---
FROM rockylinux:9 AS ebpf-builder

# Installation des outils de compilation eBPF
RUN dnf install -y epel-release && \
    dnf install -y \
        clang \
        llvm \
        bpftool \
        kernel-headers \
        libbpf-devel \
        make \
        && \
    dnf clean all

WORKDIR /build

# Copier les sources eBPF
COPY services/ja4ebpf/bpf/ ./bpf/

# Créer le répertoire des headers et générer vmlinux.h depuis le BTF du kernel
RUN mkdir -p bpf/headers && \
    bpftool btf dump file /sys/kernel/btf/vmlinux format c > bpf/headers/vmlinux.h 2>/dev/null || \
    echo "/* vmlinux.h placeholder — généré au runtime */" > bpf/headers/vmlinux.h

# --- Stage 2 : Go builder ---
FROM rockylinux:9 AS go-builder

# Installation de Go et des outils nécessaires
RUN dnf install -y epel-release && \
    dnf install -y \
        golang \
        clang \
        llvm \
        libbpf-devel \
        kernel-headers \
        bpftool \
        make \
        && \
    dnf clean all

WORKDIR /build

# Copier les headers eBPF générés au stage précédent
COPY --from=ebpf-builder /build/bpf/headers/ ./services/ja4ebpf/bpf/headers/

# Copier le workspace Go complet (nécessaire pour go.work)
COPY go.work go.work.sum ./
COPY shared/go/ja4common/ ./shared/go/ja4common/
COPY services/ja4ebpf/ ./services/ja4ebpf/

WORKDIR /build/services/ja4ebpf

# Générer les bindings Go depuis le bytecode eBPF
RUN go generate ./internal/loader/

# Compilation du binaire final
RUN CGO_ENABLED=0 go build -ldflags="-s -w" -o /out/ja4ebpf ./cmd/ja4ebpf/

# --- Stage 3 : image finale ---
FROM rockylinux:9-minimal AS final

# Copier uniquement le binaire compilé
COPY --from=go-builder /out/ja4ebpf /usr/local/bin/ja4ebpf

# Créer le répertoire de configuration
RUN mkdir -p /etc/ja4ebpf

ENTRYPOINT ["/usr/local/bin/ja4ebpf"]
