# Dockerfile for benchmark runner
# Uses pure Go build with purego for dynamic libsecp256k1 loading
# Fetches latest tag from git repository for stable builds

# Use Debian-based Go image to match runtime stage (avoids musl/glibc linker mismatch)
FROM golang:1.25-bookworm AS builder

# Install build dependencies (no secp256k1 build needed)
RUN apt-get update && apt-get install -y --no-install-recommends git ca-certificates && rm -rf /var/lib/apt/lists/*

# Set working directory
WORKDIR /build

# Clone the repository and checkout the latest tag
# Using git.nostrdev.com (primary repo, most up-to-date)
RUN git clone https://git.nostrdev.com/mleku/git.smesh.lol/orly.git . && \
    LATEST_TAG=$(git describe --tags --abbrev=0 2>/dev/null || echo "main") && \
    echo "Building benchmark from ORLY version: ${LATEST_TAG}" && \
    git checkout "${LATEST_TAG}"

# Remove local replace directives and update to released version, then download dependencies
RUN sed -i '/^replace .* => \/home/d' go.mod && \
    sed -i 's/git.smesh.lol\/mleku\/nostr v1.0.7/git.smesh.lol\/mleku\/nostr v1.0.8/' go.mod && \
    go mod tidy && \
    go mod download

# Build the benchmark tool with CGO disabled (uses purego for crypto)
RUN CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -o benchmark ./cmd/benchmark

# Final stage
# Use Debian slim instead of Alpine because Debian's libsecp256k1 includes
# Schnorr signatures (secp256k1_schnorrsig_*) and ECDH which Nostr requires.
# Alpine's libsecp256k1 is built without these modules.
FROM debian:bookworm-slim

# Install runtime dependencies
RUN apt-get update && \
    apt-get install -y --no-install-recommends ca-certificates curl libsecp256k1-1 && \
    rm -rf /var/lib/apt/lists/*

WORKDIR /app

# Copy benchmark binary (libsecp256k1.so.1 is already installed via apt)
COPY --from=builder /build/benchmark /app/benchmark

# Copy benchmark runner script from the local code
COPY --from=builder /build/cmd/benchmark/benchmark-runner.sh /app/benchmark-runner

# Make scripts executable
RUN chmod +x /app/benchmark-runner

# Create runtime user and reports directory owned by uid 1000
RUN useradd -m -u 1000 appuser && \
    mkdir -p /reports && \
    chown -R 1000:1000 /app /reports

# Environment variables
ENV BENCHMARK_EVENTS=50000
ENV BENCHMARK_WORKERS=24
ENV BENCHMARK_DURATION=60s

# Drop privileges: run as uid 1000
USER 1000:1000

# Run the benchmark runner
CMD ["/app/benchmark-runner"]
