# syntax=docker/dockerfile:1
#
# Remote machine: runs codelldb as a DAP server. The developer station's
# nvim-dap connects to it over TCP and sends a standard DAP "launch"
# request — codelldb starts the program locally, so there is no
# gdbserver entry-point assembly issue and source paths resolve cleanly.
#
# Build (run from repository root):
#   docker build -t dap-debug-remote -f remote/Dockerfile .

FROM alpine:latest

ARG CODELLDB_VERSION=1.12.2

RUN apk add --no-cache \
        build-base cmake gdb \
        curl unzip gcompat socat

WORKDIR /project
COPY common/project/ /project/

# Build with full debug info for a meaningful debugging experience.
RUN mkdir -p build \
 && cd build \
 && cmake -DCMAKE_BUILD_TYPE=Debug .. \
 && make -j"$(nproc)"

# codelldb DAP adapter — a glibc binary; gcompat provides the compatibility
# layer so it runs on musl/Alpine.
RUN mkdir -p /opt/codelldb \
 && curl -fsSL "https://github.com/vadimcn/codelldb/releases/download/v${CODELLDB_VERSION}/codelldb-linux-x64.vsix" \
    -o /tmp/codelldb.vsix \
 && cd /opt/codelldb && unzip -q /tmp/codelldb.vsix \
 && rm /tmp/codelldb.vsix \
 && chmod +x /opt/codelldb/extension/adapter/codelldb

# codelldb needs __res_init / __res_ninit (glibc DNS resolver init) which
# gcompat does not provide.  A tiny no-op shim fills the gap, then a wrapper
# script applies LD_PRELOAD transparently.
RUN printf 'int __res_init(void) { return 0; }\nint __res_ninit(void *s) { (void)s; return 0; }\n' \
        > /tmp/resolv_shim.c \
 && gcc -shared -fPIC -o /usr/lib/libresolv_compat.so /tmp/resolv_shim.c \
 && rm /tmp/resolv_shim.c \
 && mv /opt/codelldb/extension/adapter/codelldb \
       /opt/codelldb/extension/adapter/codelldb.bin \
 && printf '#!/bin/sh\nLD_PRELOAD=/usr/lib/libresolv_compat.so exec /opt/codelldb/extension/adapter/codelldb.bin "$@"\n' \
        > /opt/codelldb/extension/adapter/codelldb \
 && chmod +x /opt/codelldb/extension/adapter/codelldb

COPY remote/entrypoint.sh /entrypoint.sh

EXPOSE 13000

ENTRYPOINT ["/entrypoint.sh"]
