# Relay server image.
#
# TARGETARCH is supplied by buildx and lets one build produce images for
# amd64, arm64 and arm — the relay is pure Go with no cgo, so cross-compiling
# is just a matter of setting GOARCH.
FROM --platform=$BUILDPLATFORM golang:1.26-alpine AS builder

ARG TARGETARCH
ARG TARGETVARIANT

WORKDIR /app

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

COPY . .

# TARGETVARIANT carries the ARM version ("v6", "v7") for 32-bit ARM images.
RUN GOARM=$(echo "$TARGETVARIANT" | tr -d 'v') \
    CGO_ENABLED=0 GOOS=linux GOARCH=$TARGETARCH \
    go build -ldflags="-s -w" -o /usb-relay ./cmd/usb-relay/

FROM alpine:3.21

RUN apk add --no-cache ca-certificates

COPY --from=builder /usb-relay /usr/local/bin/usb-relay

# The relay holds no state and needs no privileges.
RUN adduser -D -u 10001 relay
USER relay

EXPOSE 8443

HEALTHCHECK --interval=30s --timeout=5s --retries=3 \
    CMD wget -q --spider http://localhost:8443/health || exit 1

ENTRYPOINT ["usb-relay"]
CMD ["--port", "8443"]
