## lint image
FROM golangci/golangci-lint:latest

RUN mkdir -p /build
WORKDIR /build
COPY ./ ./
RUN golangci-lint run

## build image:
FROM golang:1.22-alpine AS builder

# Install build dependencies including gcc for CGO
RUN apk add --no-cache git make gcc musl-dev sqlite-dev

# Set working directory
WORKDIR /build

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

# Copy source code
COPY . .

# Build the application with CGO enabled for SQLite
RUN CGO_ENABLED=1 GOOS=linux go build -a -installsuffix cgo -o webhooker cmd/webhooker/main.go

## output image:
FROM alpine:latest

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

# Create non-root user
RUN addgroup -g 1000 -S webhooker && \
    adduser -u 1000 -S webhooker -G webhooker

# Set working directory
WORKDIR /app

# Copy binary from builder
COPY --from=builder /build/webhooker .

# Change ownership
RUN chown -R webhooker:webhooker /app

# Switch to non-root user
USER webhooker

# Expose port
EXPOSE 8080

# Health check
HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \
    CMD wget --no-verbose --tries=1 --spider http://localhost:8080/.well-known/healthcheck.json || exit 1

# Run the application
CMD ["./webhooker"]
