# =============================================================================
# felhom-controller Dockerfile
# Multi-stage build: Go binary + minimal runtime
# Supports amd64 (N100 mini PCs) and arm64 (Raspberry Pi)
# =============================================================================

# --- Build stage ---
FROM golang:1.24-bookworm AS builder

ARG TARGETOS=linux
ARG TARGETARCH
ARG VERSION=dev
ARG GIT_COMMIT=unknown

WORKDIR /build

# Cache dependencies first
COPY go.mod ./
RUN go mod download || true

# Copy source
COPY . .

# Generate go.sum and ensure all deps are fetched
RUN go mod tidy

# Build static binary
RUN CGO_ENABLED=0 GOOS=${TARGETOS} GOARCH=${TARGETARCH} go build \
    -ldflags="-s -w \
        -X main.Version=${VERSION} \
        -X main.BuildTime=$(date -u +%Y-%m-%dT%H:%M:%SZ) \
        -X main.GitCommit=${GIT_COMMIT}" \
    -o /build/felhom-controller \
    ./cmd/controller/

# --- Runtime stage ---
FROM debian:bookworm-slim

# Install runtime dependencies:
# - docker-cli: for "docker compose" commands
# - ca-certificates: for HTTPS (healthchecks pings, git)
# - restic: for backup operations
# - postgresql-client: for pg_dump
# - default-mysql-client: for mysqldump
# - sqlite3: for SQLite backup
# - git: for stack sync from Gitea
# - curl: for health pings and debugging
RUN apt-get update && apt-get install -y --no-install-recommends \
    ca-certificates \
    curl \
    gnupg \
    git \
    restic \
    postgresql-client \
    default-mysql-client \
    sqlite3 \
    && rm -rf /var/lib/apt/lists/*

# Install docker-cli (without daemon)
RUN curl -fsSL https://download.docker.com/linux/debian/gpg | gpg --dearmor -o /usr/share/keyrings/docker.gpg \
    && echo "deb [arch=$(dpkg --print-architecture) signed-by=/usr/share/keyrings/docker.gpg] \
       https://download.docker.com/linux/debian bookworm stable" > /etc/apt/sources.list.d/docker.list \
    && apt-get update \
    && apt-get install -y --no-install-recommends docker-ce-cli docker-compose-plugin \
    && rm -rf /var/lib/apt/lists/*

# Create non-root user (but we'll run as root for Docker socket access)
# The Docker socket requires root or docker group membership
RUN mkdir -p /opt/docker/felhom-controller/data

COPY --from=builder /build/felhom-controller /usr/local/bin/felhom-controller

# Copy baked-in app assets (logos, screenshots)
# These are synced from the felhom.eu website repo before building.
# See: make sync-assets
COPY assets/ /usr/share/felhom/assets/

# Health check
HEALTHCHECK --interval=30s --timeout=5s --start-period=10s --retries=3 \
    CMD curl -f http://localhost:8080/api/health || exit 1

EXPOSE 8080

ENTRYPOINT ["/usr/local/bin/felhom-controller"]
CMD ["--config", "/opt/docker/felhom-controller/controller.yaml"]