# Application Engine - GoHoarder Server
# Multi-stage build to compile with CGO support
ARG TARGETOS=linux
ARG TARGETARCH=amd64

# Build stage
FROM --platform=$TARGETOS/$TARGETARCH golang:1.23-alpine AS builder

# Install build dependencies for CGO
RUN apk add --no-cache \
    gcc \
    g++ \
    musl-dev \
    sqlite-dev \
    git

WORKDIR /build

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

# Copy source code
COPY . .

# Build with CGO enabled
ARG TARGETOS
ARG TARGETARCH
ARG VERSION=dev
ARG GIT_COMMIT=unknown
ARG BUILD_TIME=unknown

RUN CGO_ENABLED=1 GOOS=$TARGETOS GOARCH=$TARGETARCH \
    go build -ldflags="-s -w \
    -X github.com/lukaszraczylo/gohoarder/internal/version.Version=${VERSION} \
    -X github.com/lukaszraczylo/gohoarder/internal/version.GitCommit=${GIT_COMMIT} \
    -X github.com/lukaszraczylo/gohoarder/internal/version.BuildTime=${BUILD_TIME}" \
    -o gohoarder ./cmd/gohoarder

# Runtime stage
FROM alpine:latest

# Install runtime dependencies (including CGO/SQLite dependencies)
RUN apk add --no-cache \
    ca-certificates \
    tzdata \
    sqlite-libs \
    musl \
    && update-ca-certificates

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

# Create necessary directories with proper permissions
RUN mkdir -p /var/cache/gohoarder \
             /var/lib/gohoarder/metadata \
             /tmp/gohoarder && \
    chown -R gohoarder:gohoarder /var/cache/gohoarder \
                                  /var/lib/gohoarder \
                                  /tmp/gohoarder && \
    chmod -R 750 /var/cache/gohoarder \
                 /var/lib/gohoarder

# Copy binary from builder
COPY --from=builder /build/gohoarder /usr/local/bin/gohoarder
RUN chmod +x /usr/local/bin/gohoarder

# Copy example config
COPY config.yaml.example /etc/gohoarder/config.yaml.example

WORKDIR /var/cache/gohoarder
USER gohoarder

# Expose ports
# 8080: Main proxy port
# 9090: Metrics/health port
EXPOSE 8080 9090

# Health check
HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 \
    CMD ["/usr/local/bin/gohoarder", "version"] || exit 1

# Run the server
ENTRYPOINT ["/usr/local/bin/gohoarder"]
CMD ["serve"]
