# Multi-stage build for nerd-monitor agent
FROM golang:1.24.4-alpine AS builder

WORKDIR /app

# Install build dependencies
RUN apk add --no-cache git make

# Copy go mod files
COPY go.mod go.sum ./

# Download dependencies
RUN go mod download

# Copy source code
COPY . .

# Build the agent binary (no templ needed for agent)
RUN CGO_ENABLED=0 GOOS=linux go build -ldflags="-w -s" -o nerd-monitor-agent ./cmd/agent

# Runtime stage
FROM alpine:latest

WORKDIR /app

COPY --from=builder /app/nerd-monitor-agent .

# Create entrypoint script BEFORE switching users
RUN echo '#!/bin/sh' > /app/entrypoint.sh && \
    echo 'SERVER=${SERVER:-localhost:8080}' >> /app/entrypoint.sh && \
    echo 'INTERVAL=${INTERVAL:-15s}' >> /app/entrypoint.sh && \
    echo 'AGENT_ID=${AGENT_ID:-}' >> /app/entrypoint.sh && \
    echo 'if [ -z "$AGENT_ID" ]; then' >> /app/entrypoint.sh && \
    echo '  exec ./nerd-monitor-agent --server "$SERVER" --interval "$INTERVAL"' >> /app/entrypoint.sh && \
    echo 'else' >> /app/entrypoint.sh && \
    echo '  exec ./nerd-monitor-agent --server "$SERVER" --interval "$INTERVAL" --id "$AGENT_ID"' >> /app/entrypoint.sh && \
    echo 'fi' >> /app/entrypoint.sh && \
    chmod +x /app/entrypoint.sh

# Create non-root user
RUN addgroup -g 1000 appgroup && adduser -D -u 1000 -G appgroup appuser
USER appuser

# Run the agent
ENTRYPOINT ["/app/entrypoint.sh"]
