#syntax=docker/dockerfile:1.7.1@sha256:a57df69d0ea827fb7266491f2813635de6f17269be881f696fbfdf2d83dda33e

FROM debian:trixie-slim@sha256:a72b4433de1cf7d6bae0c4cee74d0547f58601a643b3375f070c51600d63b6b2 AS binary

ARG REL_VERSION
ARG BINARY_VARIANT=default
ARG TARGETOS
ARG TARGETARCH
ARG GITHUB_REPOSITORY=spiceai/spiceai
# sha256 of the downloaded release asset. When set, the build fails on any
# other file. spiced_docker.yml passes the sha256 publish_release recorded.
ARG SPICED_SHA256=

RUN if [ -z "$REL_VERSION" ]; then echo "REL_VERSION build-arg is required" >&2; exit 1; fi

RUN apt-get update \
    && apt-get install --yes --no-install-recommends ca-certificates curl tar \
    && rm -rf /var/lib/{apt,dpkg,cache,log}

ENV REL_VERSION=${REL_VERSION}
ENV BINARY_VARIANT=${BINARY_VARIANT}

RUN set -eux; \
    case "${TARGETOS}" in \
      ""|linux) os_slug=linux ;; \
      *) echo "Unsupported TARGETOS: ${TARGETOS}" >&2; exit 1 ;; \
    esac; \
    case "${TARGETARCH}" in \
      amd64) arch_slug=x86_64 ;; \
      arm64) arch_slug=aarch64 ;; \
      "") arch_slug=x86_64 ;; \
      *) echo "Unsupported TARGETARCH: ${TARGETARCH}" >&2; exit 1 ;; \
    esac; \
    if [ "${BINARY_VARIANT}" = "default" ]; then \
      asset="spiced_${os_slug}_${arch_slug}.tar.gz"; \
    else \
      variant_slug=$(printf '%s' "${BINARY_VARIANT}" | tr '[:upper:]' '[:lower:]' | tr '-' '_'); \
      asset="spiced_${variant_slug}_${os_slug}_${arch_slug}.tar.gz"; \
    fi; \
    base_url="https://github.com/${GITHUB_REPOSITORY}/releases/download/v${REL_VERSION}/${asset}"; \
    if ! curl -fSLo /tmp/spiced.tar.gz "${base_url}"; then \
      if [ "${BINARY_VARIANT}" = "odbc" ]; then \
        asset="spiced_odbc_models_${os_slug}_${arch_slug}.tar.gz"; \
        base_url="https://github.com/${GITHUB_REPOSITORY}/releases/download/v${REL_VERSION}/${asset}"; \
        curl -fSLo /tmp/spiced.tar.gz "${base_url}"; \
      else \
        echo "Failed to download release asset from ${base_url}" >&2; \
        exit 1; \
      fi; \
    fi; \
    if [ -n "${SPICED_SHA256}" ]; then echo "${SPICED_SHA256}  /tmp/spiced.tar.gz" | sha256sum -c -; fi; \
    tar -C /root -xzf /tmp/spiced.tar.gz; \
    chmod +x /root/spiced; \
    rm -f /tmp/spiced.tar.gz

# PDFium is dlopen'd at runtime by the document parser (not linked into spiced),
# so ship the shared library next to the binary. The release tag must match
# PDFIUM_RELEASE_TAG in liteparse-pdfium-sys (chromium/7897).
RUN set -eux; \
    case "${TARGETARCH}" in \
      amd64|"") pdfium_asset=pdfium-linux-x64; pdfium_sha256=af96f21fd8e9d53955013dad1d17b003d0120025e787b7ce611a685d57287594 ;; \
      arm64) pdfium_asset=pdfium-linux-arm64; pdfium_sha256=e81ec447dd00097eb2fc26cff88be53ea321495711a43af9ea7b50bebdea9226 ;; \
      *) echo "Unsupported TARGETARCH for pdfium: ${TARGETARCH}" >&2; exit 1 ;; \
    esac; \
    curl -fSLo /tmp/pdfium.tgz "https://github.com/run-llama/pdfium-binaries/releases/download/chromium%2F7897/${pdfium_asset}.tgz"; \
    echo "${pdfium_sha256}  /tmp/pdfium.tgz" | sha256sum -c -; \
    mkdir -p /tmp/pdfium; \
    tar -C /tmp/pdfium -xzf /tmp/pdfium.tgz; \
    cp /tmp/pdfium/lib/libpdfium.so /root/libpdfium.so; \
    rm -rf /tmp/pdfium /tmp/pdfium.tgz

# `duckdb:` and `ducklake:` datasets read through the DuckDB library installed
# on the host, loaded by name at runtime. Keep DUCKDB_VERSION at the newest
# release test/duckdb_versions.json lists.
ARG DUCKDB_VERSION=2.0.0
ARG DUCKDB_SHA256_AMD64=993ad89e7dfca66cd6da994c2cad090c2fc160ddf9f550498a098ab4bb13cfb1
ARG DUCKDB_SHA256_ARM64=c60eecf91143ca6bbac55c4f4d40dc22520488b0ac257c86e0fe9a2b451cf2b7
RUN set -eux; \
    case "${TARGETARCH}" in \
      amd64|"") duckdb_platform=linux-amd64; duckdb_sha256="${DUCKDB_SHA256_AMD64}" ;; \
      arm64) duckdb_platform=linux-arm64; duckdb_sha256="${DUCKDB_SHA256_ARM64}" ;; \
      *) echo "Unsupported TARGETARCH for libduckdb: ${TARGETARCH}" >&2; exit 1 ;; \
    esac; \
    curl -fSLo /tmp/libduckdb.tar.gz "https://github.com/duckdb/duckdb/releases/download/v${DUCKDB_VERSION}/duckdb-shared-libs-${duckdb_platform}.tar.gz"; \
    echo "${duckdb_sha256}  /tmp/libduckdb.tar.gz" | sha256sum -c -; \
    tar -C /root -xzf /tmp/libduckdb.tar.gz libduckdb.so; \
    rm -f /tmp/libduckdb.tar.gz

FROM debian:trixie-slim@sha256:a72b4433de1cf7d6bae0c4cee74d0547f58601a643b3375f070c51600d63b6b2 AS sandbox-setup

ARG CARGO_FEATURES=default
ARG INSTALL_ORACLE_ODPIC=false
ARG ORACLE_INSTANTCLIENT_SHA256_AMD64=05b4c01c77521eee32c89550d3a2e2f4d9f9601a79af96da441dfdd2d2a32ec4
ARG ORACLE_INSTANTCLIENT_SHA256_ARM64=1d27641f16df1b1384f5d61cdcbd95a5ca57ba5d25ed881edde56543f8c6d135
# Set to a unique value per release build (spiced_docker.yml passes the run id)
# so this layer is never replayed from the GHA build cache. The CA bundle and
# every library ldd copies into the sandbox below come from this layer.
ARG APT_CACHE_BUST=

# Install required packages
RUN echo "apt cache bust: ${APT_CACHE_BUST}" \
    && apt-get update \
    && DEBIAN_FRONTEND=noninteractive apt-get upgrade --yes --no-install-recommends \
    && apt-get install --yes --no-install-recommends ca-certificates libssl3 findutils tzdata \
    && if echo "$CARGO_FEATURES" | grep -q "odbc"; then \
      apt-get install --yes --no-install-recommends unixodbc; \
    fi \
    && rm -rf /var/lib/{apt,dpkg,cache,log}

# Layout a tiny filesystem in /spice_sandbox
RUN mkdir -p /spice_sandbox/bin \
    && mkdir -p /spice_sandbox/lib \
    && mkdir -p /spice_sandbox/usr/lib \
    && mkdir -p /spice_sandbox/usr/local/bin \
    && mkdir -p /spice_sandbox/usr/share \
    && mkdir -p /spice_sandbox/etc \
    && mkdir -p /spice_sandbox/etc/ssl \
    && mkdir -p /spice_sandbox/dev \
    && mkdir -p /spice_sandbox/app

# Copy the binary
COPY --from=binary /root/spiced /spice_sandbox/usr/local/bin/

# Copy PDFium (used for PDF document parsing). liteparse dlopen's it at runtime,
# so it is not linked into spiced and is not reported by ldd; ship it next to the
# binary where the loader's "next to the executable" search path finds it.
COPY --from=binary /root/libpdfium.so /spice_sandbox/usr/local/bin/

# Copy CA certificates
RUN cp -r /etc/ssl/certs /spice_sandbox/etc/ssl/certs

# Copy timezone database (IANA tzdb) - used by jiff, chrono, libc, and other timezone-aware libraries
RUN cp -r /usr/share/zoneinfo /spice_sandbox/usr/share/zoneinfo

# Copy every dependent library reported by ldd
# The sed removes trailing colons/parens that appear in ldd output, and grep -v filters memory addresses
RUN ldd /spice_sandbox/usr/local/bin/spiced | grep -o '/[^ ]*' | sed 's/[:)]$//' | grep -v '^/spice_sandbox' | sort -u | xargs -I '{}' sh -c 'mkdir -p /spice_sandbox/$(dirname "{}") && cp "{}" "/spice_sandbox{}"'

# Copy PDFium's own shared-library dependencies (a subset of spiced's, but sweep
# explicitly since ldd on spiced does not see the dlopen'd PDFium)
RUN ldd /spice_sandbox/usr/local/bin/libpdfium.so | grep -o '/[^ ]*' | sed 's/[:)]$//' | grep -v '^/spice_sandbox' | sort -u | xargs -I '{}' sh -c 'mkdir -p /spice_sandbox/$(dirname "{}") && cp "{}" "/spice_sandbox{}"'

# Copy libduckdb, loaded by name at runtime for `duckdb:` and `ducklake:`, onto
# the default library path, with its own shared-library dependencies (ldd on
# spiced does not see it)
COPY --from=binary /root/libduckdb.so /spice_sandbox/usr/lib/libduckdb.so
RUN ldd /spice_sandbox/usr/lib/libduckdb.so | grep -o '/[^ ]*' | sed 's/[:)]$//' | grep -v '^/spice_sandbox' | sort -u | xargs -I '{}' sh -c 'mkdir -p /spice_sandbox/$(dirname "{}") && cp "{}" "/spice_sandbox{}"'

# Copy additional required libraries
RUN find /lib /usr/lib -name 'libpthread.so.0' -exec sh -c 'mkdir -p /spice_sandbox/$(dirname "{}") && cp "{}" "/spice_sandbox{}"' \;
RUN find /lib /usr/lib -name 'librt.so.1' -exec sh -c 'mkdir -p /spice_sandbox/$(dirname "{}") && cp "{}" "/spice_sandbox{}"' \;
RUN find /lib /usr/lib -name 'libdl.so.2' -exec sh -c 'mkdir -p /spice_sandbox/$(dirname "{}") && cp "{}" "/spice_sandbox{}"' \;

# Preinstall Oracle ODPI-C (if enabled)
RUN if [ "$INSTALL_ORACLE_ODPIC" = "true" ]; then \
    set -euo pipefail; \
    apt-get update && apt-get install -y --no-install-recommends libaio1 unzip curl; \
    ARCH=$(dpkg --print-architecture); \
    if [ "$ARCH" = "amd64" ]; then \
      : "${ORACLE_INSTANTCLIENT_SHA256_AMD64:?ORACLE_INSTANTCLIENT_SHA256_AMD64 must be set to the expected SHA256 checksum}"; \
      curl -fsSLo basic.zip https://download.oracle.com/otn_software/linux/instantclient/2380000/instantclient-basiclite-linux.x64-23.8.0.25.04.zip; \
      echo "${ORACLE_INSTANTCLIENT_SHA256_AMD64}  basic.zip" | sha256sum -c -; \
    elif [ "$ARCH" = "arm64" ]; then \
      : "${ORACLE_INSTANTCLIENT_SHA256_ARM64:?ORACLE_INSTANTCLIENT_SHA256_ARM64 must be set to the expected SHA256 checksum}"; \
      curl -fsSLo basic.zip https://download.oracle.com/otn_software/linux/instantclient/2380000/instantclient-basiclite-linux.arm64-23.8.0.25.04.zip; \
      echo "${ORACLE_INSTANTCLIENT_SHA256_ARM64}  basic.zip" | sha256sum -c -; \
    else \
      echo "Unsupported architecture: $ARCH" >&2; exit 1; \
    fi; \
    unzip basic.zip && \
    cp -v \
      instantclient_*/libclntsh.so.23.1 \
      instantclient_*/libclntshcore.so.23.1 \
      instantclient_*/libnnz.so \
      instantclient_*/libociicus.so \
      instantclient_*/fips.so \
      instantclient_*/legacy.so \
      /spice_sandbox/usr/lib && \
    ln -s libclntsh.so.23.1 /spice_sandbox/usr/lib/libclntsh.so && \
    ln -s libclntshcore.so.23.1 /spice_sandbox/usr/lib/libclntshcore.so && \
    cp "$(find /usr/lib /lib -name 'libaio.so.1' | head -n 1)" /spice_sandbox/usr/lib && \
    cp "$(find /usr/lib /lib -name 'libresolv.so.2' | head -n 1)" /spice_sandbox/usr/lib && \
    rm -f basic.zip; \
  fi

# Minimal passwd & group for the nobody user
RUN echo 'nobody:x:65534:65534:nobody:/app:/usr/sbin/nologin' > /spice_sandbox/etc/passwd \
    && echo 'nogroup:x:65534:' > /spice_sandbox/etc/group

# Create DuckDB directory in sandbox
RUN mkdir -p /spice_sandbox/.duckdb \
    && chmod 755 /spice_sandbox/.duckdb

# Create a world-writable /tmp for temporary and spill files
RUN mkdir -p /spice_sandbox/tmp \
    && chmod 1777 /spice_sandbox/tmp

# Give the nobody user ownership of app dir
RUN chown -R 65534:65534 /spice_sandbox/app

# Create HuggingFace cache directory in sandbox
RUN mkdir -p /spice_sandbox/.cache/huggingface/hub \
    && chown -R 65534:65534 /spice_sandbox/.cache \
    && chmod -R 755 /spice_sandbox/.cache

FROM scratch

COPY --from=sandbox-setup /spice_sandbox/ /

USER 65534:65534

EXPOSE 8090 50051

WORKDIR /app

ENV HOME=/app
ENV HF_HOME=/.cache/huggingface
ENV HF_HUB_CACHE=/.cache/huggingface/hub
ENV SSL_CERT_FILE=/etc/ssl/certs/ca-certificates.crt
ENV SSL_CERT_DIR=/etc/ssl/certs

ENTRYPOINT ["/usr/local/bin/spiced"]