# syntax=docker/dockerfile:1.7

FROM golang:1.27.1-alpine AS builder
WORKDIR /src

RUN apk add --no-cache ca-certificates tzdata

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

COPY . .

ARG TARGETOS
ARG TARGETARCH
RUN XTEVE_VERSION="$(grep -m1 '^#### ' changelog-beta.md | cut -d' ' -f2 | sed 's/-beta$//')" \
  && test -n "$XTEVE_VERSION" \
  && CGO_ENABLED=0 GOOS=$TARGETOS GOARCH=$TARGETARCH \
  go build -trimpath -ldflags="-s -w -X main.Version=$XTEVE_VERSION" -o /out/xteve ./xteve.go

# Static ffmpeg/ffprobe binaries. To bump, pick a tag from
# https://hub.docker.com/r/mwader/static-ffmpeg/tags and change it here.
FROM mwader/static-ffmpeg:7.1.1 AS ffmpeg

FROM alpine:3.23

# Build-time defaults for the xteve user. The entrypoint can change them at
# runtime with PUID/PGID, so these only matter when neither is set.
ARG XTEVE_UID=1000
ARG XTEVE_GID=1000

RUN apk add --no-cache ca-certificates tzdata su-exec \
  && addgroup -S -g "${XTEVE_GID}" xteve \
  && adduser -S -D -H -u "${XTEVE_UID}" -G xteve xteve \
  && mkdir -p /xteve/config \
  && chown -R xteve:xteve /xteve

WORKDIR /xteve

COPY --from=builder /out/xteve /usr/local/bin/xteve
COPY --from=ffmpeg /ffmpeg /usr/local/bin/ffmpeg
COPY --from=ffmpeg /ffprobe /usr/local/bin/ffprobe
COPY docker/entrypoint.sh /usr/local/bin/docker-entrypoint.sh

# The entrypoint starts as root so it can apply PUID/PGID and fix ownership of
# the config directory, then drops to the xteve user with su-exec.

EXPOSE 34400/tcp

ENV XTEVE_CONFIG=/xteve/config
ENV XTEVE_PORT=34400

VOLUME ["/xteve/config"]

HEALTHCHECK --interval=30s --timeout=5s --start-period=30s --retries=3 \
  CMD wget -qO- "http://127.0.0.1:${XTEVE_PORT}/healthz" > /dev/null || exit 1

ENTRYPOINT ["/usr/local/bin/docker-entrypoint.sh"]
