# Multi-stage build for nerd-monitor server
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 . .

# Generate templ templates
RUN go run github.com/a-h/templ/cmd/templ@latest generate

# Build the server binary
RUN CGO_ENABLED=0 GOOS=linux go build -ldflags="-w -s" -o nerd-monitor-server ./cmd/server

# Runtime stage
FROM alpine:latest

WORKDIR /app

# Install ca-certificates for HTTPS
RUN apk add --no-cache ca-certificates

# Copy binary from builder
COPY --from=builder /app/nerd-monitor-server .

# Create entrypoint script BEFORE switching users
RUN echo '#!/bin/sh' > /app/entrypoint.sh && \
    echo 'ADDR=${ADDR:-0.0.0.0}' >> /app/entrypoint.sh && \
    echo 'PORT=${PORT:-8080}' >> /app/entrypoint.sh && \
    echo 'USERNAME=${USERNAME:-admin}' >> /app/entrypoint.sh && \
    echo 'PASSWORD=${PASSWORD:-admin}' >> /app/entrypoint.sh && \
    echo 'exec ./nerd-monitor-server -addr "$ADDR" -port "$PORT" -username "$USERNAME" -password "$PASSWORD"' >> /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

# Expose port
EXPOSE 8080

# Health check
HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \
    CMD wget --quiet --tries=1 --spider http://localhost:8080/login || exit 1

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