# Multi-stage build for mosis-portal
FROM golang:1.22-alpine AS builder

WORKDIR /build

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

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

# Copy source code
COPY . .

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

# Final image
FROM alpine:3.19

WORKDIR /app

# Install runtime dependencies
RUN apk add --no-cache ca-certificates tzdata

# Install Litestream
RUN wget -q https://github.com/benbjohnson/litestream/releases/download/v0.3.13/litestream-v0.3.13-linux-amd64.tar.gz && \
    tar -xzf litestream-v0.3.13-linux-amd64.tar.gz && \
    mv litestream /usr/local/bin/ && \
    rm litestream-v0.3.13-linux-amd64.tar.gz

# Copy binary from builder
COPY --from=builder /build/mosis-portal /app/mosis-portal

# Copy Litestream config
COPY litestream.yml /etc/litestream.yml

# Create data directories
RUN mkdir -p /data /packages /backups

# 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/health || exit 1

# Run with Litestream for continuous backup
ENTRYPOINT ["litestream", "replicate", "-exec", "/app/mosis-portal"]
