# Dopbase : image a partir du binaire officiel des releases GitHub.
# Reprend les etapes de https://dopbase.com/install.sh (sans la telemetrie Umami) :
# resolution de version -> checksums.txt -> archive -> SHA-256 -> extraction du seul membre
# "dopbase" -> controle "dopbase --version".
# Le binaire Linux est un executable musl statique (static-pie) : aucune dependance glibc.

# Tag de release (sans prefixe v, ex: 0.1.10) ou "latest"
ARG DOPBASE_VERSION=0.1.10

# --- 1. Telechargement et verification ---------------------------------------
FROM alpine:3.22 AS fetch
ARG DOPBASE_VERSION
ARG TARGETARCH
RUN apk add --no-cache curl
WORKDIR /tmp/dl
RUN set -eu; \
    repo="https://github.com/dopbase/dopbase"; \
    dl() { curl --fail --show-error --silent --location --connect-timeout 10 --retry 3 "$@"; }; \
    # Architecture : TARGETARCH (buildx) sinon uname -m
    case "${TARGETARCH:-$(uname -m)}" in \
      amd64|x86_64)  arch=amd64 ;; \
      arm64|aarch64) arch=arm64 ;; \
      *) echo "Architecture non supportee : ${TARGETARCH:-$(uname -m)}" >&2; exit 1 ;; \
    esac; \
    # Version : figee, ou resolue via la redirection de /releases/latest
    if [ "${DOPBASE_VERSION}" = latest ]; then \
      tag=$(dl --head --output /dev/null --write-out '%{url_effective}' "${repo}/releases/latest"); \
      tag=${tag##*/}; \
    else \
      tag=${DOPBASE_VERSION}; \
    fi; \
    version=${tag#v}; \
    echo "${version}" | grep -Eq '^[0-9]+\.[0-9]+\.[0-9]+$' || { echo "Version invalide : ${tag}" >&2; exit 1; }; \
    archive="dopbase_${version}_linux_${arch}.tar.gz"; \
    base="${repo}/releases/download/${tag}"; \
    dl --output checksums.txt "${base}/checksums.txt"; \
    expected=$(awk -v a="${archive}" '$2 == a { n++; c = $1 } END { if (n != 1 || length(c) != 64) exit 1; print c }' checksums.txt); \
    dl --output "${archive}" "${base}/${archive}"; \
    echo "${expected}  ${archive}" | sha256sum -c -; \
    tar -tzf "${archive}" | grep -qx dopbase; \
    tar -xOzf "${archive}" dopbase > /tmp/dopbase; \
    chmod 755 /tmp/dopbase; \
    reported=$(/tmp/dopbase --version); \
    [ "${reported}" = "v${version}" ] || { echo "Attendu v${version}, le binaire annonce ${reported}" >&2; exit 1; }

# --- 2. Runtime --------------------------------------------------------------
FROM alpine:3.22
# UID 10001 identique a la variante "src" : le volume /data est interchangeable.
RUN apk add --no-cache ca-certificates \
    && addgroup -S -g 10001 dopbase \
    && adduser -S -D -H -u 10001 -G dopbase -h /data -s /sbin/nologin dopbase \
    && mkdir /data && chown dopbase:dopbase /data

COPY --from=fetch /tmp/dopbase /usr/local/bin/dopbase

ENV DOPBASE_DATA_DIR=/data \
    DOPBASE_HOST=0.0.0.0 \
    DOPBASE_PORT=8840

USER dopbase
VOLUME ["/data"]
EXPOSE 8840

ENTRYPOINT ["dopbase"]
CMD ["server", "start"]
