# syntax=docker/dockerfile:1.7

ARG BUN_IMAGE=oven/bun:1-alpine
ARG ALPINE_IMAGE=alpine:3.22

FROM ${BUN_IMAGE} AS deps
WORKDIR /app

COPY package.json bun.lock ./
RUN bun install --frozen-lockfile

FROM deps AS build
WORKDIR /app

COPY . .

ARG TARGETARCH
RUN set -eux; \
    case "${TARGETARCH:-$(uname -m)}" in \
      amd64|x86_64) export BUN_TARGET=bun-linux-x64-musl ;; \
      arm64|aarch64) export BUN_TARGET=bun-linux-arm64-musl ;; \
      *) echo "不支持的架构: ${TARGETARCH:-$(uname -m)}" >&2; exit 1 ;; \
    esac; \
    bun run build

FROM ${ALPINE_IMAGE} AS runtime

RUN apk add --no-cache ca-certificates iputils-ping libgcc libstdc++ tzdata \
    && addgroup -S dial \
    && adduser -S -G dial -h /nonexistent -s /sbin/nologin dial \
    && mkdir -p /etc/dial /data/dial \
    && chown -R dial:dial /data/dial

COPY --from=build --chmod=0755 /app/dist/dial-server /usr/local/bin/dial-server
COPY --chmod=0644 docker/probes.yaml /etc/dial/probes.yaml

USER dial
WORKDIR /data/dial

EXPOSE 3000
HEALTHCHECK --interval=30s --timeout=5s --start-period=10s --retries=3 \
  CMD wget -q -O - "http://127.0.0.1:3000/health" >/dev/null || exit 1

ENTRYPOINT ["/usr/local/bin/dial-server"]
CMD ["/etc/dial/probes.yaml"]
