# Build stage
FROM golang:1.22-alpine AS builder

WORKDIR /app

# Install build dependencies
RUN apk add --no-cache git ca-certificates

# Copy go mod and source files
COPY go.mod main.go ./

# Tidy and download dependencies (generates go.sum)
RUN go mod tidy && go mod download && go mod verify

# Build static binary
RUN CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build \
    -ldflags="-w -s" \
    -o lifecycle-sidecar \
    main.go

# Runtime stage
FROM alpine:3.19

# Install procps for process monitoring (pgrep, kill)
RUN apk add --no-cache procps ca-certificates

# Create non-root user
RUN addgroup -g 1000 sidecar && \
    adduser -D -u 1000 -G sidecar sidecar

WORKDIR /app

# Copy binary from builder
COPY --from=builder /app/lifecycle-sidecar /app/lifecycle-sidecar

# Run as non-root
USER sidecar

ENTRYPOINT ["/app/lifecycle-sidecar"]
