FROM golang:1.26-bookworm AS build

ARG TARGETOS=linux
ARG TARGETARCH=amd64

WORKDIR /src

COPY go.mod go.sum ./
RUN go mod download

COPY cmd/ cmd/
COPY internal/ internal/
COPY migrations/ migrations/
COPY web/ web/

RUN CGO_ENABLED=1 GOOS=${TARGETOS} GOARCH=${TARGETARCH} go build -trimpath -ldflags="-s -w" -o /out/update-server ./cmd/server
RUN CGO_ENABLED=1 GOOS=${TARGETOS} GOARCH=${TARGETARCH} go build -trimpath -ldflags="-s -w" -o /out/update-migrate ./cmd/migrate

FROM debian:bookworm-slim

RUN apt-get update \
	&& apt-get install -y --no-install-recommends ca-certificates sqlite3 tzdata \
	&& rm -rf /var/lib/apt/lists/*

RUN groupadd --system --gid 10001 update-server \
	&& useradd --system --uid 10001 --gid 10001 --home /nonexistent --shell /usr/sbin/nologin update-server

WORKDIR /app

COPY --from=build /out/update-server /usr/local/bin/update-server
COPY --from=build /out/update-migrate /usr/local/bin/update-migrate
COPY migrations/ ./migrations/
COPY web/ ./web/

RUN mkdir -p /data \
	&& chown -R update-server:update-server /app /data

ENV APP_ADDR=0.0.0.0:8080 \
	DATA_DIR=/data \
	SQLITE_PATH=/data/db.sqlite \
	ARTIFACTS_DIR=/data/artifacts \
	MIGRATIONS_DIR=/app/migrations \
	TEMPLATES_DIR=/app/web/templates \
	STATIC_DIR=/app/web/static \
	TRUST_PROXY_HEADERS=true \
	APP_READ_TIMEOUT=30s \
	APP_READ_HEADER_TIMEOUT=5s \
	APP_WRITE_TIMEOUT=60s \
	APP_IDLE_TIMEOUT=120s \
	APP_MAX_HEADER_BYTES=1048576 \
	APP_LOGIN_RATE_LIMIT_PER_MINUTE=10 \
	APP_LOGIN_RATE_LIMIT_BURST=5 \
	APP_CLIENT_RATE_LIMIT_PER_MINUTE=120 \
	APP_CLIENT_RATE_LIMIT_BURST=60

VOLUME ["/data"]
EXPOSE 8080

USER update-server:update-server

ENTRYPOINT ["update-server"]

