# syntax=docker/dockerfile:1.7-labs
# =============================================================================
# Jupyter Podman Rootless - Containerfile (multistage build: 3-stage runtime chain + toolbox-builder aux stage)
# Project: SpecWeave Jupyter + Podman(rootless) Development Container
# Base: ubuntu:26.04 | OpenSSH Server + Jupyter Lab/Notebook + Podman(rootless)
# Python: Miniforge3 (conda-forge) at /opt/conda (Python 3.14 cp314t free-threading, libmamba solver)
# Locale: zh_CN.UTF-8 / Timezone: Asia/Shanghai
# Non-root user: devuser (fixed UID/GID 1000; stock ubuntu account removed first,
#                mirrors upstream toolbox images/ubuntu/26.04/Containerfile userdel)
# Services: sshd(22) + jupyter(8888), managed by supervisord; podman(rootless) for user
#
# Build stages:
#   Stage 1/3: base-runtime     - 系统运行时基础（Ubuntu + APT包 + locale/tz + Podman）
#   Stage 2/3: conda-builder    - Miniforge下载 + main环境创建 + podman-py/podman-compose本地源安装 + 深度清理（隔离构建环境）
#   Stage 3/3: final            - COPY --from=conda-builder /opt/conda + COPY --from=toolbox-builder toolbox + 用户/配置/验证
#   Stage (aux): toolbox-builder - 独立Go构建阶段（golang:1.26-bookworm），仅构建toolbox二进制供final COPY，不进final
#
# Build: podman build -t jupyter-podman-rootless .
# CN:    podman build --build-arg APT_MIRROR=aliyun --build-arg PIP_MIRROR=aliyun --build-arg CONDA_MIRROR=tuna -t jupyter-podman-rootless .
# JPMan: jpman build / jpman rebuild（内部自动附加 --format docker + tuna 镜像）
#
# ⚠ SHELL 指令兼容性约束：
#   OCI 格式下 SHELL 指令被 Podman 忽略，RUN 步骤以 /bin/sh 执行。
#   因此所有 RUN 步骤必须兼容 POSIX sh（禁止使用 <<<、read -ra、数组语法等 bash 特有特性）。
#   若需使用 bash 高级语法，构建命令须显式加 --format docker 使 SHELL 指令生效。
#   jpman 已内置 --format docker，无需手动指定。
# Run:   podman run -d --device /dev/fuse --security-opt label=disable -p 2222:22 -p 8888:8888 \
#          -e USER_PASSWORD=pass -e JUPYTER_TOKEN=mysecret -v $(pwd)/workspace:/workspace jupyter-podman-rootless
# Debug: podman run -it --rm --device /dev/fuse --security-opt label=disable jupyter-podman-rootless bash
#
# Runtime Stage Layering (final stage, dockerfile-runtime-logical-layering pattern v1.4):
#   Layer 1/5: 从base-runtime继承（系统包+locale+tz+Podman） (变化频率: 最低)
#   Layer 2/5: COPY --from=conda-builder /opt/conda + COPY --from=toolbox-builder /out/toolbox → /usr/local/libexec/toolbox (变化频率: 低)
#   Layer 3/5: 用户创建 + subuid/subgid + 目录权限 + Podman配置 (变化频率: 中)
#   Layer 4/5: 配置文件COPY + 权限设置 + 语法验证 (变化频率: 高)
#   Layer 5/5: 最终元数据 + 清理 + 最终验证 (变化频率: 最低)
#
# Build Timing: 每个Stage结束时输出 [TIMER]，最终final阶段输出汇总表
# =============================================================================

ARG APT_MIRROR=official
ARG PIP_MIRROR=official
ARG CONDA_MIRROR=official
ARG PYTHON_VERSION=3.14
ARG PYTHON_BUILD=cp314t

# ═══════════════════════════════════════════════════════════════════
# Stage 1/3: base-runtime — 系统运行时基础（不含构建工具）
# 变化频率：最低
# 原则：--no-install-recommends，仅安装运行时必需的系统包，同层清理apt lists
# ═══════════════════════════════════════════════════════════════════
FROM ubuntu:26.04 AS base-runtime

ARG APT_MIRROR

LABEL maintainer="SpecWeave"
LABEL com.github.containers.toolbox="true" \
      com.github.debarshiray.toolbox="true" \
      usage="This image is compatible with toolbox create/enter (Toolbx interactive dev container)"

ENV DEBIAN_FRONTEND=noninteractive \
    TZ=Asia/Shanghai \
    LANG=zh_CN.UTF-8 \
    LANGUAGE=zh_CN:zh \
    LC_ALL=zh_CN.UTF-8 \
    CONDA_DIR=/opt/conda \
    CONDA_DEFAULT_ENV=main \
    PATH="/opt/conda/envs/main/bin:/opt/conda/bin:${PATH}" \
    PYTHONDONTWRITEBYTECODE=1 \
    NON_ROOT_USER=devuser \
    JUPYTER_PORT=8888 \
    SSH_PORT=22 \
    GRANT_SUDO=no \
    ALLOW_ROOT_SSH=no

SHELL ["/bin/bash", "-e", "-o", "pipefail", "-c"]

RUN echo "=== Stage 1/3: base-runtime — Install system packages + Chinese locale + Podman ===" && \
    _STAGE_START=$(date +%s) && \
    echo "[TIMER] base-runtime stage started at $(date -u +%Y-%m-%dT%H:%M:%SZ)" && \
    echo "START=$_STAGE_START" > /tmp/.build-timer && \
    echo "[BUILD] Configuring APT mirror: ${APT_MIRROR:-official}" && \
    if [ "${APT_MIRROR}" = "aliyun" ]; then \
        sed -i 's|http://archive.ubuntu.com|http://mirrors.aliyun.com|g; s|http://security.ubuntu.com|http://mirrors.aliyun.com|g' /etc/apt/sources.list.d/ubuntu.sources 2>/dev/null || \
        sed -i 's|http://archive.ubuntu.com|http://mirrors.aliyun.com|g; s|http://security.ubuntu.com|http://mirrors.aliyun.com|g' /etc/apt/sources.list 2>/dev/null || true; \
        echo "[BUILD] Using Aliyun APT mirror"; \
    elif [ "${APT_MIRROR}" = "tuna" ]; then \
        sed -i 's|http://archive.ubuntu.com|http://mirrors.tuna.tsinghua.edu.cn|g; s|http://security.ubuntu.com|http://mirrors.tuna.tsinghua.edu.cn|g' /etc/apt/sources.list.d/ubuntu.sources 2>/dev/null || \
        sed -i 's|http://archive.ubuntu.com|http://mirrors.tuna.tsinghua.edu.cn|g; s|http://security.ubuntu.com|http://mirrors.tuna.tsinghua.edu.cn|g' /etc/apt/sources.list 2>/dev/null || true; \
        echo "[BUILD] Using Tsinghua TUNA APT mirror"; \
    else \
        echo "[BUILD] Using official APT sources"; \
    fi && \
    apt-get update -qq && \
    echo "[INFO] Installing RUNTIME packages (--no-install-recommends, no build tools)..." && \
    apt-get install -y --no-install-recommends -qq \
        binutils \
        ca-certificates \
        bzip2 \
        xz-utils \
        locales \
        openssh-server \
        openssh-client \
        procps \
        pwgen \
        sudo \
        supervisor \
        tini \
        tzdata \
        vim-tiny \
        curl \
        git \
        podman \
        crun \
        conmon \
        uidmap \
        fuse-overlayfs \
        slirp4netns \
        passt \
        libcap2-bin \
        flatpak-xdg-utils \
    && echo "[OK] Runtime system packages installed" && \
    echo "[BUILD] Asserting critical runtime binaries (guards against silent no-op apt install)..." && \
    for _b in sshd sudo podman crun conmon tini supervisord fuse-overlayfs slirp4netns; do \
        command -v "$_b" >/dev/null 2>&1 || { echo "[ERROR] Missing runtime binary: $_b (apt install did not take effect; check APT_MIRROR=${APT_MIRROR:-official})"; exit 1; }; \
    done && \
    echo "[OK] Critical runtime binaries verified: sshd sudo podman crun conmon tini supervisord fuse-overlayfs slirp4netns" && \
    echo "[BUILD] Linking flatpak-spawn for Toolbx host callback (mirrors upstream images/ubuntu/26.04/Containerfile)..." && \
    ln -sf /usr/libexec/flatpak-xdg-utils/flatpak-spawn /usr/bin/flatpak-spawn && \
    test -x /usr/bin/flatpak-spawn && echo "[OK] flatpak-spawn available (/usr/bin/flatpak-spawn)" && \
    echo "[INFO] Verifying key runtime package versions:" && \
    echo "  - git: $(git --version 2>/dev/null | awk '{print $3}')" && \
    echo "  - openssh-server: $(dpkg-query -W -f='${Version}' openssh-server 2>/dev/null || echo 'N/A')" && \
    echo "  - podman: $(podman --version 2>/dev/null | awk '{print $3}')" && \
    echo "  - crun: $(crun --version 2>/dev/null | head -1 | awk '{print $2}')" && \
    echo "  - fuse-overlayfs: $(fuse-overlayfs --version 2>/dev/null | head -1 | awk '{print $2}')" && \
    echo "  - slirp4netns: $(slirp4netns --version 2>/dev/null | head -1 | awk '{print $3}')" && \
    echo "  - pasta: $(pasta --version 2>/dev/null | head -1 | awk '{print $NF}')" && \
    echo "  - flatpak-xdg-utils: $(dpkg-query -W -f='${Version}' flatpak-xdg-utils 2>/dev/null || echo 'N/A')" && \
    echo "[BUILD] Generating zh_CN.UTF-8 locale..." && \
    sed -i 's/^# *zh_CN.UTF-8 UTF-8/zh_CN.UTF-8 UTF-8/' /etc/locale.gen && \
    locale-gen zh_CN.UTF-8 && \
    update-locale LANG=zh_CN.UTF-8 && \
    ln -sf /usr/share/zoneinfo/Asia/Shanghai /etc/localtime && \
    echo "Asia/Shanghai" > /etc/timezone && \
    echo "[BUILD] zh_CN locale + Asia/Shanghai timezone ready" && \
    echo "[STRIP] Stripping Podman binaries (same-layer, no COW)..." && \
    for _bin in /usr/bin/podman /usr/bin/crun /usr/bin/conmon; do \
        [ -f "$_bin" ] && strip --strip-all "$_bin" 2>/dev/null || true; \
    done && \
    for _bin in /usr/libexec/podman/rootlessport /usr/libexec/podman/quadlet; do \
        [ -f "$_bin" ] && strip --strip-all "$_bin" 2>/dev/null || true; \
    done && \
    rm -f /usr/libexec/podman/podman-testing 2>/dev/null || true && \
    echo "[OK] Podman binaries stripped" && \
    rm -rf /var/lib/apt/lists/* && \
    _NOW=$(date +%s) && \
    _ELAPSED=$((_NOW - _STAGE_START)) && \
    echo "BASE=$_NOW" >> /tmp/.build-timer && \
    echo "[TIMER] Stage 1/3 base-runtime took ${_ELAPSED}s"

# ═══════════════════════════════════════════════════════════════════
# Stage (aux): toolbox-builder — 构建 toolbox 真二进制（final 安装至 /usr/local/libexec/toolbox）
# 变化频率：低（仅当 pinned upstream/toolbox 源树变更时重建）
# 产物：/out/toolbox，仅供 final 阶段 COPY --from；源树与 Go 工具链均不进 final
# 原则：golang 官方镜像基于 Debian bookworm（glibc 2.36 <= final ubuntu:26.04，二进制向下兼容）；
#       官方镜像自带 gcc/libc6-dev/make（cgo 就绪），额外仅需 libsubid-dev（shadow/subid.h 头文件，
#       供 toolbox cgo subid wrapper 编译；libsubid 运行时经 dlopen 懒加载，不静态链接）；
#       go.mod 声明 go 1.22.0 且官方镜像 GOTOOLCHAIN=local，故选当前稳定版 golang:1.26 以覆盖
#       依赖图中所有 module 的 go 指令（向上取稳定 tag，不自动升级工具链）
# ═══════════════════════════════════════════════════════════════════
FROM golang:1.26-bookworm AS toolbox-builder

ARG GO_PROXY=https://goproxy.cn,direct

# 仅限本阶段新增 ENV（构建态），不进 final
ENV GOPROXY=${GO_PROXY} \
    CGO_ENABLED=1

SHELL ["/bin/bash", "-e", "-o", "pipefail", "-c"]

RUN echo "=== Stage (aux): toolbox-builder — Install cgo build deps (libsubid-dev headers) ===" && \
    _STAGE_START=$(date +%s) && \
    echo "[TIMER] toolbox-builder stage started at $(date -u +%Y-%m-%dT%H:%M:%SZ)" && \
    echo "[INFO] go toolchain: $(go version)" && \
    apt-get update -qq && \
    echo "[INFO] Installing libsubid-dev (provides shadow/subid.h for toolbox cgo subid wrapper)..." && \
    apt-get install -y --no-install-recommends -qq libsubid-dev && \
    rm -rf /var/lib/apt/lists/* && \
    echo "[OK] toolbox-builder cgo build deps installed"

COPY upstream/toolbox/src /toolbox-src

RUN echo "=== Stage (aux): toolbox-builder — go build toolbox (module root: /toolbox-src) ===" && \
    _STAGE_START=$(date +%s) && \
    cd /toolbox-src && \
    echo "[INFO] Resolving Go modules via GOPROXY (versions pinned by go.sum)..." && \
    go build -trimpath -buildvcs=false \
        -ldflags "-s -w -X github.com/containers/toolbox/pkg/version.currentVersion=0.3" \
        -o /out/toolbox . && \
    echo "[OK] /out/toolbox built (stripped -s -w): $(ls -lh /out/toolbox | awk '{print $5}')" && \
    /out/toolbox --version && echo "[OK] /out/toolbox --version works (binary liveness only; host forwarding needs Toolbx launcher)" && \
    echo "[CLEAN] Removing Go module/build cache and source tree from toolbox-builder layer..." && \
    rm -rf /go/pkg/mod /root/.cache/go-build /toolbox-src && \
    _NOW=$(date +%s) && \
    _ELAPSED=$((_NOW - _STAGE_START)) && \
    echo "[TIMER] Stage (aux) toolbox-builder took ${_ELAPSED}s"

# ═══════════════════════════════════════════════════════════════════
# Stage 2/3: conda-builder — Miniforge + conda环境构建（隔离构建阶段）
# 变化频率：低
# 原则：此阶段包含curl/wget等下载工具和binutils（strip），仅用于构建/opt/conda；
#       此阶段的层全部不进入最终镜像，仅/opt/conda通过COPY --from进入final
# ═══════════════════════════════════════════════════════════════════
FROM ubuntu:26.04 AS conda-builder

ARG CONDA_MIRROR
ARG PIP_MIRROR
ARG PYTHON_VERSION
ARG PYTHON_BUILD

ENV DEBIAN_FRONTEND=noninteractive \
    CONDA_DIR=/opt/conda \
    CONDA_DEFAULT_ENV=main \
    PATH="/opt/conda/envs/main/bin:/opt/conda/bin:${PATH}" \
    PYTHONDONTWRITEBYTECODE=1

SHELL ["/bin/bash", "-e", "-o", "pipefail", "-c"]

# podman-py + podman-compose: pinned upstream source trees（由构建前置 stage 机制放入 <context>/upstream/<name>，
# .containerignore 已放行其 README.md）。仅在本阶段装入 main env；源目录在下方 RUN 内安装完成后即删除，
# 源树与 pip 缓存均不进 final 镜像
COPY upstream/podman-py ./upstream-podman-py
COPY upstream/podman-compose ./upstream-podman-compose

# Local installer cache: pre-downloaded Miniforge3 installers placed by the operator
# at <context>/local-cache/miniforge/Miniforge3-Linux-<arch>.sh. Consulted BEFORE any
# network source so offline/air-gapped builds work and GitHub throttling cannot break
# the build (see the resolver in the conda-builder RUN below, which reads
# /tmp/local-cache/miniforge/Miniforge3-Linux-<arch>.sh).
# COPY <src>/ <dst>/ copies the *contents* of src, so /tmp/local-cache/miniforge/ keeps
# the miniforge/ level. Tracked placeholder .gitkeep keeps this COPY valid when the
# cache is empty.
COPY local-cache/ /tmp/local-cache/

RUN echo "=== Stage 2/3: conda-builder — Install build tools + Miniforge3 + create main env ===" && \
    _STAGE_START=$(date +%s) && \
    echo "[TIMER] conda-builder stage started at $(date -u +%Y-%m-%dT%H:%M:%SZ)" && \
    apt-get update -qq && \
    echo "[INFO] Installing BUILD tools (curl/wget/binutils for strip, bzip2/xz for archives)..." && \
    apt-get install -y --no-install-recommends -qq \
        curl \
        wget \
        bzip2 \
        xz-utils \
        binutils \
        ca-certificates \
    && echo "[OK] Build tools installed" && \
    echo "[INFO] Detecting architecture..." && \
    ARCH=$(uname -m) && \
    case "$ARCH" in \
        x86_64)  CONDA_ARCH="x86_64" ;; \
        aarch64) CONDA_ARCH="aarch64" ;; \
        *) echo "[ERROR] Unsupported architecture: $ARCH"; exit 1 ;; \
    esac && \
    echo "[OK] Architecture: $ARCH ($CONDA_ARCH)" && \
    echo "[INFO] Resolving Miniforge3 installer (local cache -> mirrors -> official)..." && \
    DL_OK=0 && \
    _LOCAL_INSTALLER="/tmp/local-cache/miniforge/Miniforge3-Linux-${CONDA_ARCH}.sh" && \
    _DL_GH="https://github.com/conda-forge/miniforge/releases/latest/download/Miniforge3-Linux-${CONDA_ARCH}.sh" && \
    _DL_TUNA="https://mirrors.tuna.tsinghua.edu.cn/github-release/conda-forge/miniforge/LatestRelease/Miniforge3-Linux-${CONDA_ARCH}.sh" && \
    _DL_ALIYUN="https://mirrors.aliyun.com/github-release/conda-forge/miniforge/LatestRelease/Miniforge3-Linux-${CONDA_ARCH}.sh" && \
    _DL_USTC="https://mirrors.ustc.edu.cn/github-release/conda-forge/miniforge/LatestRelease/Miniforge3-Linux-${CONDA_ARCH}.sh" && \
    if [ -s "${_LOCAL_INSTALLER}" ]; then \
        echo "[OK] Local installer cache hit: ${_LOCAL_INSTALLER} ($(stat -c%s "${_LOCAL_INSTALLER}") bytes) - skipping network download"; \
        cp "${_LOCAL_INSTALLER}" /tmp/miniforge.sh; \
        DL_OK=1; \
    fi && \
    if [ "$DL_OK" = "0" ]; then \
        case "${CONDA_MIRROR}" in \
            tuna)   _DL_URLS="${_DL_TUNA} ${_DL_ALIYUN} ${_DL_USTC} ${_DL_GH}"; \
                    echo "[BUILD] Mirror-first order (GitHub throttling avoidance): TUNA -> Aliyun -> USTC -> GitHub" ;; \
            aliyun) _DL_URLS="${_DL_ALIYUN} ${_DL_TUNA} ${_DL_USTC} ${_DL_GH}"; \
                    echo "[BUILD] Mirror-first order (GitHub throttling avoidance): Aliyun -> TUNA -> USTC -> GitHub" ;; \
            ustc)   _DL_URLS="${_DL_USTC} ${_DL_ALIYUN} ${_DL_TUNA} ${_DL_GH}"; \
                    echo "[BUILD] Mirror-first order (GitHub throttling avoidance): USTC -> Aliyun -> TUNA -> GitHub" ;; \
            *)      _DL_URLS="${_DL_GH}"; \
                    echo "[BUILD] Using official GitHub for Miniforge" ;; \
        esac; \
    fi && \
    if [ "$DL_OK" = "0" ]; then \
        for dl_url in ${_DL_URLS}; do \
            echo "[INFO] Trying: $dl_url"; \
            if curl -fsSL --connect-timeout 30 --max-time 600 --retry 4 --retry-delay 5 --retry-all-errors \
                -o /tmp/miniforge.sh "$dl_url" 2>/tmp/conda_dl_err.log; then \
                echo "[OK] Downloaded from: $dl_url ($(stat -c%s /tmp/miniforge.sh) bytes)"; \
                DL_OK=1; \
                break; \
            else \
                _rc=$?; \
                echo "[WARN] Failed (curl exit ${_rc}), trying next source..."; \
            fi; \
        done; \
    fi && \
    if [ "$DL_OK" = "0" ]; then \
        echo "[ERROR] Failed to resolve Miniforge3 installer from local cache and all network sources"; \
        echo "[HINT] Pre-download Miniforge3-Linux-${CONDA_ARCH}.sh and place it at local-cache/miniforge/ in the build context to build offline"; \
        cat /tmp/conda_dl_err.log; \
        exit 1; \
    fi && \
    echo "[INFO] Installing Miniforge3 to ${CONDA_DIR}..." && \
    bash /tmp/miniforge.sh -b -p "${CONDA_DIR}" -f && \
    rm -f /tmp/miniforge.sh /tmp/conda_dl_err.log && \
    echo "[OK] Miniforge3 installed: $("${CONDA_DIR}/bin/conda" --version 2>&1)" && \
    . "${CONDA_DIR}/etc/profile.d/conda.sh" && \
    echo "[ACTION] Writing system-level ${CONDA_DIR}/.condarc..." && \
    case "${CONDA_MIRROR}" in \
        tuna) \
            printf '%s\n' \
                'channels:' \
                '  - conda-forge' \
                'show_channel_urls: true' \
                'channel_priority: strict' \
                'default_channels_alias: https://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud' \
                'custom_channels:' \
                '  conda-forge: https://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud' \
                'ssl_verify: true' \
                'auto_activate_base: false' \
                'remote_connect_timeout_secs: 30' \
                'remote_read_timeout_secs: 120' \
                'remote_max_retries: 5' \
                'remote_backoff_factor: 3' \
                'repodata_threads: 8' \
                'execute_threads: 8' \
                'solver: libmamba' \
                > "${CONDA_DIR}/.condarc"; \
            ;; \
        aliyun) \
            printf '%s\n' \
                'channels:' \
                '  - conda-forge' \
                'show_channel_urls: true' \
                'channel_priority: strict' \
                'default_channels_alias: https://mirrors.aliyun.com/anaconda/cloud' \
                'custom_channels:' \
                '  conda-forge: https://mirrors.aliyun.com/anaconda/cloud' \
                'ssl_verify: true' \
                'auto_activate_base: false' \
                'remote_connect_timeout_secs: 30' \
                'remote_read_timeout_secs: 120' \
                'remote_max_retries: 5' \
                'remote_backoff_factor: 3' \
                'repodata_threads: 8' \
                'execute_threads: 8' \
                'solver: libmamba' \
                > "${CONDA_DIR}/.condarc"; \
            ;; \
        ustc) \
            printf '%s\n' \
                'channels:' \
                '  - conda-forge' \
                'show_channel_urls: true' \
                'channel_priority: strict' \
                'default_channels_alias: https://mirrors.ustc.edu.cn/anaconda/cloud' \
                'custom_channels:' \
                '  conda-forge: https://mirrors.ustc.edu.cn/anaconda/cloud' \
                'ssl_verify: true' \
                'auto_activate_base: false' \
                'remote_connect_timeout_secs: 30' \
                'remote_read_timeout_secs: 120' \
                'remote_max_retries: 5' \
                'remote_backoff_factor: 3' \
                'repodata_threads: 8' \
                'execute_threads: 8' \
                'solver: libmamba' \
                > "${CONDA_DIR}/.condarc"; \
            ;; \
        *) \
            printf '%s\n' \
                'channels:' \
                '  - conda-forge' \
                'show_channel_urls: true' \
                'channel_priority: strict' \
                'ssl_verify: true' \
                'auto_activate_base: false' \
                'remote_connect_timeout_secs: 30' \
                'remote_read_timeout_secs: 300' \
                'remote_max_retries: 5' \
                'remote_backoff_factor: 3' \
                'repodata_threads: 8' \
                'execute_threads: 8' \
                'solver: libmamba' \
                > "${CONDA_DIR}/.condarc"; \
            ;; \
    esac && \
    echo "[OK] .condarc configured" && \
    echo "[INFO] mamba version: $(mamba --version 2>&1 | head -1)" && \
    echo "[CLEAN] Removing anaconda-anon-usage telemetry..." && \
    "${CONDA_DIR}/bin/conda" remove -y -n base anaconda-anon-usage --force 2>/dev/null || true && \
    echo "[INFO] Configuring PIP mirror: ${PIP_MIRROR:-official}..." && \
    if [ "${PIP_MIRROR}" = "aliyun" ]; then \
        "${CONDA_DIR}/bin/pip" config set global.index-url https://mirrors.aliyun.com/pypi/simple/ && \
        "${CONDA_DIR}/bin/pip" config set global.trusted-host mirrors.aliyun.com; \
        echo "[BUILD] Using Aliyun PyPI mirror"; \
    elif [ "${PIP_MIRROR}" = "tuna" ]; then \
        "${CONDA_DIR}/bin/pip" config set global.index-url https://pypi.tuna.tsinghua.edu.cn/simple/ && \
        "${CONDA_DIR}/bin/pip" config set global.trusted-host pypi.tuna.tsinghua.edu.cn; \
        echo "[BUILD] Using Tsinghua TUNA PyPI mirror"; \
    else \
        echo "[BUILD] Using official PyPI"; \
    fi && \
    echo "[INFO] Creating 'main' env with Python ${PYTHON_VERSION}=*_${PYTHON_BUILD} + Jupyter (single mamba solve)..." && \
    _mamba_start=$(date +%s) && \
    mamba create -y -n main -c conda-forge --override-channels -q \
        "python=${PYTHON_VERSION}=*_${PYTHON_BUILD}" \
        "python_abi=*=*_${PYTHON_BUILD}" \
        pip \
        "jupyterlab>=4.4" \
        "notebook>=7.3" \
        ipykernel \
        nbconvert \
        jupyter_server \
        ipywidgets && \
    _mamba_elapsed=$(($(date +%s) - _mamba_start)) && \
    echo "[OK] main env created in ${_mamba_elapsed}s" && \
    echo "[OK] Python version: $(/opt/conda/envs/main/bin/python --version 2>&1 | awk '{print $2}')" && \
    echo "[OK] Jupyter version: $(/opt/conda/envs/main/bin/jupyter --version 2>&1 | head -1)" && \
    echo "[INFO] Installing OMLMD (OCI Artifact for ML model & metadata)..." && \
    /opt/conda/envs/main/bin/pip install --no-cache-dir omlmd || \
    /opt/conda/envs/main/bin/pip install --no-cache-dir --ignore-requires-python omlmd && \
    echo "[OK] omlmd installed: $(/opt/conda/envs/main/bin/python -c 'import importlib.metadata; print(importlib.metadata.version("omlmd"))' 2>&1)" && \
    echo "[INFO] Installing OLOT (KServe ModelCar packager, oras-py backend)..." && \
    /opt/conda/envs/main/bin/pip install --no-cache-dir "olot[oras-py]" || \
    /opt/conda/envs/main/bin/pip install --no-cache-dir --ignore-requires-python "olot[oras-py]" && \
    echo "[OK] olot installed: $(/opt/conda/envs/main/bin/python -c 'import importlib.metadata; print(importlib.metadata.version("olot"))' 2>&1)" && \
    echo "[INFO] Installing podman-py + podman-compose from pinned local source trees (./upstream-podman-*, into main env)..." && \
    if /opt/conda/envs/main/bin/pip install --no-cache-dir ./upstream-podman-py ./upstream-podman-compose >/tmp/podman-tools-pip.log 2>&1; then \
        echo "[OK] podman-py + podman-compose installed (runtime deps resolved via pip, PIP_MIRROR=${PIP_MIRROR:-official})"; \
    else \
        echo "[WARN] Direct pip install failed under cp314t (log: /tmp/podman-tools-pip.log) — retrying with conda-forge deps + pip --no-deps"; \
        mamba install -y -n main -c conda-forge --override-channels -q pyyaml python-dotenv requests urllib3 \
            || { echo "[ERROR] mamba fallback for podman-tools runtime deps failed"; tail -n 30 /tmp/podman-tools-pip.log; exit 1; }; \
        /opt/conda/envs/main/bin/pip install --no-cache-dir --no-deps ./upstream-podman-py ./upstream-podman-compose \
            || { echo "[ERROR] pip --no-deps install of podman-py/podman-compose failed"; tail -n 30 /tmp/podman-tools-pip.log; exit 1; }; \
        echo "[OK] podman-py + podman-compose installed via fallback (conda-forge deps + pip --no-deps)"; \
    fi && \
    rm -rf ./upstream-podman-py ./upstream-podman-compose /tmp/podman-tools-pip.log && \
    echo "[CLEAN] Removed podman-py/podman-compose source trees + pip log" && \
    echo "[OK] podman-compose version: $(/opt/conda/envs/main/bin/podman-compose --version 2>&1 | head -1)" && \
    echo "[OK] podman SDK (podman-py) version: $(/opt/conda/envs/main/bin/python -c 'import importlib.metadata; print(importlib.metadata.version("podman"))' 2>&1)" && \
    echo "[CLEAN] === DEEP CLEAN of /opt/conda (before COPY to final stage) ===" && \
    echo "[CLEAN] Removing tk/tcl from base and main env..." && \
    for env_dir in "${CONDA_DIR}" "${CONDA_DIR}/envs/main"; do \
        rm -rf "$env_dir/lib/tk8.6" "$env_dir/lib/tcl8.6" "$env_dir/lib/tk8" "$env_dir/lib/tcl8" 2>/dev/null || true; \
        rm -f "$env_dir/lib/libtk8.6.so" "$env_dir/lib/libtcl8.6.so" 2>/dev/null || true; \
        rm -f "$env_dir/bin/tclsh"* "$env_dir/bin/wish"* 2>/dev/null || true; \
    done && \
    echo "[CLEAN] Removing nbclassic (legacy frontend)..." && \
    find /opt/conda/envs/main/lib/python3.*/site-packages -type d -name "nbclassic*" -exec rm -rf {} + 2>/dev/null || true && \
    rm -f /opt/conda/envs/main/bin/jupyter-nbclassic 2>/dev/null || true && \
    echo "[CLEAN] Removing pandoc-server, pandoc-lua..." && \
    rm -f /opt/conda/envs/main/bin/pandoc-server /opt/conda/envs/main/bin/pandoc-lua 2>/dev/null || true && \
    echo "[CLEAN] Removing test directories..." && \
    for env_dir in "${CONDA_DIR}" "${CONDA_DIR}/envs/main"; do \
        find "$env_dir/lib" -type d -path "*/python*/test" -prune -exec rm -rf {} + 2>/dev/null || true; \
        find "$env_dir/lib" -type d -path "*/python*/unittest/test" -prune -exec rm -rf {} + 2>/dev/null || true; \
        find "$env_dir/lib" -type d -path "*/python*/site-packages/*/tests" -prune -exec rm -rf {} + 2>/dev/null || true; \
        find "$env_dir/lib/python3.*/test" -type d -name test -prune -exec rm -rf {} + 2>/dev/null || true; \
        find "$env_dir/lib/python3.*/site-packages" -type d -name tests -prune -exec rm -rf {} + 2>/dev/null || true; \
    done && \
    find /opt/conda/envs/main/share/jupyter -path "*/staging/node_modules" -prune -exec rm -rf {} + 2>/dev/null || true && \
    echo "[CLEAN] Removing conda package cache and index..." && \
    "${CONDA_DIR}/bin/conda" clean -a -y -q 2>/dev/null || true && \
    rm -rf "${CONDA_DIR}/pkgs"/* 2>/dev/null || true && \
    rm -rf "${CONDA_DIR}/envs/main/conda-meta/history" 2>/dev/null || true && \
    echo "[CLEAN] Removing .pyc/__pycache__..." && \
    find "${CONDA_DIR}" -type f \( -name "*.pyc" -o -name "*.pyo" \) -delete 2>/dev/null || true && \
    find "${CONDA_DIR}" -type d -name __pycache__ -exec rm -rf {} + 2>/dev/null || true && \
    echo "[CLEAN] Removing man pages, docs, info files..." && \
    rm -rf "${CONDA_DIR}/man" "${CONDA_DIR}/share/man" "${CONDA_DIR}/share/doc" "${CONDA_DIR}/info" "${CONDA_DIR}/share/info" 2>/dev/null || true && \
    for env_dir in "${CONDA_DIR}" "${CONDA_DIR}/envs/main"; do \
        rm -rf "$env_dir/share/man" "$env_dir/share/doc" "$env_dir/info" "$env_dir/share/info" 2>/dev/null || true; \
    done && \
    echo "[STRIP] Stripping ALL binaries in /opt/conda (bin + lib)..." && \
    find "${CONDA_DIR}/bin" -type f -executable ! -name "*.py" ! -name "*.sh" ! -name "*.rb" ! -name "*.pl" ! -name "*.pm" \
        -exec strip --strip-unneeded {} \; 2>/dev/null || true && \
    if [ -f "${CONDA_DIR}/micromamba/micromamba" ]; then \
        strip --strip-all "${CONDA_DIR}/micromamba/micromamba" 2>/dev/null || true; \
    fi && \
    find "${CONDA_DIR}/lib" -name "*.so*" -type f \
        -exec strip --strip-unneeded {} \; 2>/dev/null || true && \
    find "${CONDA_DIR}/sbin" "${CONDA_DIR}/libexec" -type f -executable \
        -exec strip --strip-unneeded {} \; 2>/dev/null || true && \
    for env_bin in /opt/conda/envs/main/bin /opt/conda/envs/main/lib; do \
        find "$env_bin" -type f -executable ! -name "*.py" ! -name "*.sh" \
            -exec strip --strip-unneeded {} \; 2>/dev/null || true; \
    done && \
    find /opt/conda/envs/main/lib -name "*.so*" -type f \
        -exec strip --strip-unneeded {} \; 2>/dev/null || true && \
    if [ -f /opt/conda/envs/main/bin/node ]; then \
        strip --strip-all /opt/conda/envs/main/bin/node 2>/dev/null || true; \
    fi && \
    chown -R root:root "${CONDA_DIR}" 2>/dev/null || true && \
    chmod -R a+rX "${CONDA_DIR}" 2>/dev/null || true && \
    find "${CONDA_DIR}/bin" -type f -executable -exec chmod a+x {} \; 2>/dev/null || true && \
    find /opt/conda/envs/main/bin -type f -executable -exec chmod a+x {} \; 2>/dev/null || true && \
    echo "" && \
    echo "┌─────────────────────────────────────────────────┐" && \
    echo "│  [FREE-THREADING VERIFICATION - builder]        │" && \
    echo "└─────────────────────────────────────────────────┘" && \
    /opt/conda/envs/main/bin/python -c "import sys, sysconfig; assert sysconfig.get_config_var('Py_GIL_DISABLED') == 1, 'Python is NOT a free-threading build!'; assert not sys._is_gil_enabled(), 'GIL is still enabled!'; print(f'[OK] Python {sys.version} is free-threading (cp314t confirmed, GIL disabled)')" && \
    echo "" && \
    echo "[CLEAN] Removing apt cache from builder stage (not strictly necessary but tidy)..." && \
    apt-get clean && \
    rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/* && \
    _NOW=$(date +%s) && \
    _ELAPSED=$((_NOW - _STAGE_START)) && \
    echo "[TIMER] Stage 2/3 conda-builder took ${_ELAPSED}s" && \
    echo "[INFO] /opt/conda size after deep clean: $(du -sh /opt/conda 2>/dev/null | cut -f1 || echo 'N/A')" && \
    echo "" && \
    echo "[OK] conda-builder stage complete: /opt/conda is ready for COPY --from"

# ═══════════════════════════════════════════════════════════════════
# Stage 3/3: final (runtime) — 最终运行时镜像
# 变化频率：高（配置修改）
# 原则：从base-runtime继承系统层，仅COPY成品/opt/conda，不包含任何构建工具
# ═══════════════════════════════════════════════════════════════════
FROM base-runtime AS final

LABEL description="Ubuntu 26.04 with Jupyter + Podman(rootless) + OMLMD(ML model OCI artifact) + OLOT(KServe ModelCar) + Miniforge3(Python 3.14 cp314t free-threading, conda-forge, libmamba solver), managed by supervisord"
LABEL version="2.0-ms"

# 重新声明ARG（多阶段构建中ARG作用域限定在单个FROM之前，需要在使用阶段再次声明）
ARG PYTHON_VERSION
ARG PYTHON_BUILD

SHELL ["/bin/bash", "-e", "-o", "pipefail", "-c"]

# ═══════════════════════════════════════════════════════════════════
# Layer 2/5 (final): COPY builder 产物 — /opt/conda（conda-builder）+ toolbox（toolbox-builder）
# 变化频率：低（builder 产物变更时；toolbox 为独立 Go 剥离(-s -w)二进制，变化频率最低）
# 原则：COPY整个/opt/conda目录（已在builder阶段完成清理和strip）；toolbox 仅一个可执行文件，chmod 755
#       真二进制落 /usr/local/libexec/toolbox 而非 /usr/local/bin：/usr/local/bin/toolbox 留给 Layer 4/5
#       安装的「裸跑指引包装器」（容器内无宿主 Toolbx 启动器时优雅降级），避免真二进制被 wrapper 遮蔽
# ═══════════════════════════════════════════════════════════════════
RUN echo "=== Stage 3/3: final runtime — Starting final assembly ===" && \
    _FINAL_START=$(date +%s) && \
    echo "FINAL_START=$_FINAL_START" >> /tmp/.build-timer && \
    echo ""

COPY --from=conda-builder /opt/conda /opt/conda
COPY --from=toolbox-builder /out/toolbox /usr/local/libexec/toolbox

RUN echo "=== Layer 2/5: COPY conda (/opt/conda) + toolbox (/usr/local/libexec/toolbox) ===" && \
    _STAGE_START=$(date +%s) && \
    echo "[OK] /opt/conda copied from conda-builder stage" && \
    chmod 755 /usr/local/libexec/toolbox && \
    test -x /usr/local/libexec/toolbox && echo "[OK] /usr/local/libexec/toolbox copied from toolbox-builder (real binary, chmod 755)" && \
    echo "[INFO] toolbox binary size: $(du -h /usr/local/libexec/toolbox 2>/dev/null | cut -f1 || echo 'N/A')" && \
    echo "[INFO] /usr/local/bin/toolbox (guidance wrapper, Layer 4/5) execs /usr/local/libexec/toolbox when TOOLBOX_PATH is set" && \
    echo "[INFO] Copied /opt/conda size: $(du -sh /opt/conda 2>/dev/null | cut -f1 || echo 'N/A')" && \
    echo "[INFO] conda version: $(conda --version 2>&1)" && \
    echo "[INFO] Python version: $(python --version 2>&1)" && \
    _NOW=$(date +%s) && \
    _ELAPSED=$((_NOW - _STAGE_START)) && \
    _START=$(grep '^START=' /tmp/.build-timer | cut -d= -f2) && \
    _TOTAL=$((_NOW - _START)) && \
    echo "L2=$_NOW" >> /tmp/.build-timer && \
    echo "[TIMER] Layer 2/5 (COPY conda + toolbox) took ${_ELAPSED}s | base-runtime+L2 cumulative: ${_TOTAL}s"

# ═══════════════════════════════════════════════════════════════════
# Layer 3/5: 用户创建 + subuid/subgid + 目录权限 + Podman配置
# 变化频率：中
# ═══════════════════════════════════════════════════════════════════
RUN echo "=== Layer 3/5: Create user devuser + subuid/subgid + directories + Podman config ===" && \
    _STAGE_START=$(date +%s) && \
    echo "[BUILD] Creating docker group (for compatibility)..." && \
    if ! getent group docker >/dev/null 2>&1; then \
        groupadd -r docker; \
        echo "[OK] docker group created"; \
    else \
        echo "[INFO] docker group already exists: GID=$(getent group docker | cut -d: -f3)"; \
    fi && \
    echo "[BUILD] Removing stock 'ubuntu' account (it ships with UID/GID 1000 in ubuntu:26.04)..." && \
    echo "[INFO] Mirrors upstream toolbox images/ubuntu/26.04/Containerfile: 'userdel --remove ubuntu'" && \
    if getent passwd ubuntu >/dev/null 2>&1; then \
        userdel --remove ubuntu 2>/dev/null || userdel ubuntu 2>/dev/null || true; \
        echo "[OK] stock ubuntu user removed (frees UID/GID 1000)"; \
    else \
        echo "[INFO] stock ubuntu user absent, skip userdel"; \
    fi && \
    if getent group 1000 >/dev/null 2>&1; then \
        groupdel "$(getent group 1000 | cut -d: -f1)" 2>/dev/null || true; \
    fi && \
    echo "[BUILD] Creating devuser with FIXED UID/GID 1000..." && \
    if getent passwd devuser >/dev/null 2>&1; then \
        echo "[INFO] User devuser already exists, asserting UID/GID 1000..."; \
        test "$(id -u devuser)" = "1000" && test "$(id -g devuser)" = "1000"; \
        usermod -aG sudo,docker devuser; \
    else \
        useradd -m -s /bin/bash -u 1000 -U -G sudo,docker devuser; \
    fi && \
    echo "[OK] User devuser created: UID=$(id -u devuser) GID=$(id -g devuser) groups=$(groups devuser)" && \
    echo "[BUILD] Configuring /etc/subuid and /etc/subgid for rootless Podman..." && \
    echo "devuser:100000:65536" > /etc/subuid && \
    echo "devuser:100000:65536" > /etc/subgid && \
    echo "[OK] subuid/subgid configured: devuser:100000:65536" && \
    echo "[BUILD] Creating directories..." && \
    mkdir -p /workspace /root/.jupyter /root/.ssh /home/devuser/.jupyter /home/devuser/.ssh /home/devuser/.config/containers \
        /run/sshd /var/log/supervisor /etc/supervisor/conf.d \
        /etc/containers/containers.conf.d /run/host \
        /var/lib/jpman/ssh-host-keys && \
    chmod 777 /workspace && \
    chmod 700 /home/devuser/.ssh /root/.ssh /var/lib/jpman/ssh-host-keys && \
    chown -R devuser:devuser /home/devuser/.jupyter /home/devuser/.ssh /home/devuser/.config && \
    echo "[OK] Directories created with proper permissions" && \
    echo "[BUILD] Creating Toolbx compatibility markers..." && \
    touch /run/.toolboxenv /run/.containerenv /etc/hosts /etc/resolv.conf /etc/machine-id && \
    echo "[OK] Toolbx markers: /run/.toolboxenv, /run/.containerenv, /run/host" && \
    echo "[BUILD] Configuring conda initialization..." && \
    echo "# Initialize conda for login shells" > /etc/profile.d/conda-init.sh && \
    echo ". /opt/conda/etc/profile.d/conda.sh" >> /etc/profile.d/conda-init.sh && \
    echo "conda activate main" >> /etc/profile.d/conda-init.sh && \
    chmod +x /etc/profile.d/conda-init.sh && \
    echo "[OK] /etc/profile.d/conda-init.sh created" && \
    echo "[BUILD] Creating B-scheme host socket bridge for independent shells..." && \
    printf '%s\n' \
        '# B-scheme: bridge independent shells (SSH login / podman exec / Jupyter/IDE' \
        '# terminals / cron) to the host rootless podman socket. SSH sessions are' \
        '# spawned by sshd+PAM and do NOT inherit container-config env vars, so the' \
        '# bridge must not rely solely on HOST_PODMAN_SOCK being present.' \
        '# Resolution order:' \
        '#   1. explicit CONTAINER_HOST wins (tcp/remote/local daemon escape hatch)' \
        '#   2. HOST_PODMAN_SOCK env (container config; visible in podman exec and the' \
        '#      entrypoint -> supervisord -> jupyter process subtree)' \
        '#   3. /etc/podman-host-sock.path (resolved path written by entrypoint.sh;' \
        '#      survives sshd/PAM environment scrubbing; covers non-standard mounts)' \
        '#   4. standard runtime socket /run/user/<uid>/podman/podman.sock' \
        '# No-op when no socket exists (in-container rootless fallback unaffected).' \
        'if [ -z "${CONTAINER_HOST:-}" ]; then' \
        '    _hps_sock="${HOST_PODMAN_SOCK:-}"' \
        '    if [ -z "${_hps_sock}" ] && [ -r /etc/podman-host-sock.path ]; then' \
        '        _hps_sock="$(cat /etc/podman-host-sock.path 2>/dev/null)"' \
        '    fi' \
        '    if [ -z "${_hps_sock}" ]; then' \
        '        _hps_cand="/run/user/$(id -u)/podman/podman.sock"' \
        '        [ -S "${_hps_cand}" ] && _hps_sock="${_hps_cand}"' \
        '        unset _hps_cand' \
        '    fi' \
        '    if [ -n "${_hps_sock}" ] && [ -S "${_hps_sock}" ]; then' \
        '        export CONTAINER_HOST="unix://${_hps_sock}"' \
        '    fi' \
        '    unset _hps_sock' \
        'fi' \
        > /etc/profile.d/80-podman-host-socket.sh && \
    chmod 644 /etc/profile.d/80-podman-host-socket.sh && \
    bash -n /etc/profile.d/80-podman-host-socket.sh && \
    echo "[OK] /etc/profile.d/80-podman-host-socket.sh created" && \
    echo "[BUILD] Configuring devuser .bashrc..." && \
    echo ". /opt/conda/etc/profile.d/conda.sh" >> /home/devuser/.bashrc && \
    echo "conda activate main" >> /home/devuser/.bashrc && \
    echo "# B-scheme bridge for non-login interactive shells (Jupyter/IDE terminals)" >> /home/devuser/.bashrc && \
    echo "[ -r /etc/profile.d/80-podman-host-socket.sh ] && . /etc/profile.d/80-podman-host-socket.sh" >> /home/devuser/.bashrc && \
    chown devuser:devuser /home/devuser/.bashrc && \
    echo "[OK] devuser .bashrc configured (conda + B-scheme bridge)" && \
    echo "[BUILD] Configuring /etc/environment PATH..." && \
    echo "PATH=/opt/conda/envs/main/bin:/opt/conda/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin" >> /etc/environment && \
    echo "BASH_ENV=/etc/profile.d/80-podman-host-socket.sh" >> /etc/environment && \
    echo "[OK] /etc/environment updated (PATH + BASH_ENV for PAM-scrubbed SSH shells)" && \
    echo "[BUILD] Creating Podman rootless configuration..." && \
    printf '%s\n' \
        '[containers]' \
        'cgroup_manager = "cgroupfs"' \
        'events_logger = "file"' \
        'log_driver = "k8s-file"' \
        '' \
        '[engine]' \
        'cgroup_manager = "cgroupfs"' \
        'events_logger = "file"' \
        > /etc/containers/containers.conf.d/rootless.conf && \
    echo "[OK] /etc/containers/containers.conf.d/rootless.conf created" && \
    echo "[BUILD] Creating user-level storage.conf for fuse-overlayfs..." && \
    printf '%s\n' \
        '[storage]' \
        'driver = "overlay"' \
        'runroot = ""' \
        'graphroot = ""' \
        '' \
        '[storage.options]' \
        'additionalimagestores = []' \
        '' \
        '[storage.options.overlay]' \
        'mount_program = "/usr/bin/fuse-overlayfs"' \
        'mountopt = "nodev,metacopy=on"' \
        'skip_mount_home = "false"' \
        '' \
        '[storage.options.thinpool]' \
        > /home/devuser/.config/containers/storage.conf && \
    chown devuser:devuser /home/devuser/.config/containers/storage.conf && \
    chmod 644 /home/devuser/.config/containers/storage.conf && \
    echo "[OK] User-level storage.conf configured for fuse-overlayfs" && \
    echo "[OK] BASH_ENV bridge prepared (activated via ENV for non-interactive shells)" && \
    echo "[BUILD] Configuring sudo for devuser (NOPASSWD)..." && \
    echo "devuser ALL=(ALL) NOPASSWD:ALL" > /etc/sudoers.d/devuser && \
    chmod 0440 /etc/sudoers.d/devuser && \
    echo "[OK] sudoers configured for devuser (NOPASSWD)" && \
    _NOW=$(date +%s) && \
    _ELAPSED=$((_NOW - _STAGE_START)) && \
    _START=$(grep '^START=' /tmp/.build-timer | cut -d= -f2) && \
    _TOTAL=$((_NOW - _START)) && \
    echo "L3=$_NOW" >> /tmp/.build-timer && \
    echo "[TIMER] Layer 3/5 (user+subuid+perms+podman-config) took ${_ELAPSED}s | Cumulative: ${_TOTAL}s"

# 非交互 bash（podman exec ... bash -c / cron / 脚本）不读 profile.d 也不读
# .bashrc；BASH_ENV 令其 source 同一桥接脚本。脚本内含守卫，socket 缺失时 no-op。
ENV BASH_ENV=/etc/profile.d/80-podman-host-socket.sh

# ═══════════════════════════════════════════════════════════════════
# Layer 4/5: 配置文件COPY + 权限设置 + 语法验证
# 变化频率：高
# ═══════════════════════════════════════════════════════════════════
COPY config/sshd_config /etc/ssh/sshd_config
COPY config/supervisord.conf /etc/supervisor/supervisord.conf
COPY config/supervisor/conf.d/ /etc/supervisor/conf.d/
COPY config/jupyter_notebook_config.py /root/.jupyter/jupyter_notebook_config.py
COPY config/jupyter_notebook_config.py /home/devuser/.jupyter/jupyter_notebook_config.py
COPY config/containers/storage.conf /etc/containers/storage.conf
COPY --chmod=755 entrypoint.sh /usr/local/bin/entrypoint.sh
COPY --chmod=755 scripts/healthcheck.sh /usr/local/bin/healthcheck.sh
COPY --chmod=755 scripts/olot_car.py /usr/local/bin/olot_car.py
COPY --chmod=755 scripts/toolbox-wrapper.sh /usr/local/bin/toolbox

RUN echo "=== Layer 4/5: Install configs, fix permissions, validate syntax ===" && \
    _STAGE_START=$(date +%s) && \
    echo "[BUILD] Setting permissions on config files..." && \
    chown -R devuser:devuser /home/devuser/.jupyter && \
    chmod 600 /home/devuser/.jupyter/jupyter_notebook_config.py 2>/dev/null || true && \
    chown root:root /root/.jupyter/jupyter_notebook_config.py && \
    chmod 644 /root/.jupyter/jupyter_notebook_config.py && \
    echo "[BUILD] Converting CRLF to LF for all scripts and configs..." && \
    for f in /usr/local/bin/entrypoint.sh /usr/local/bin/healthcheck.sh /usr/local/bin/olot_car.py /usr/local/bin/toolbox; do \
        if [ -f "$f" ]; then \
            sed -i 's/\r$//' "$f"; \
            echo "[OK] CRLF stripped: $f"; \
        fi; \
    done && \
    chmod +x /usr/local/bin/entrypoint.sh /usr/local/bin/healthcheck.sh /usr/local/bin/olot_car.py /usr/local/bin/toolbox && \
    echo "" && \
    echo "┌─────────────────────────────────────────────────┐" && \
    echo "│  [VALIDATION CHECKPOINT - Layer 4/5]            │" && \
    echo "│  Running syntax validation for all configs      │" && \
    echo "└─────────────────────────────────────────────────┘" && \
    echo "[VALIDATE 1/7] sshd -t (SSH daemon config syntax)..." && \
    sshd -t && echo "[OK] sshd_config syntax valid" && \
    echo "[VALIDATE 2/7] bash -n entrypoint.sh (shell syntax)..." && \
    bash -n /usr/local/bin/entrypoint.sh && echo "[OK] entrypoint.sh bash syntax valid" && \
    echo "[VALIDATE 3/7] bash -n healthcheck.sh (shell syntax)..." && \
    bash -n /usr/local/bin/healthcheck.sh && echo "[OK] healthcheck.sh bash syntax valid" && \
    echo "[VALIDATE 4/7] python py_compile olot_car.py (Python syntax)..." && \
    python -c "import py_compile; py_compile.compile('/usr/local/bin/olot_car.py', doraise=True)" && echo "[OK] olot_car.py Python syntax valid" && \
    echo "[VALIDATE 5/7] bash -n toolbox wrapper (shell syntax)..." && \
    bash -n /usr/local/bin/toolbox && echo "[OK] toolbox wrapper bash syntax valid" && \
    echo "[VALIDATE 6/7] Checking supervisord config..." && \
    test -f /etc/supervisor/supervisord.conf && echo "[OK] supervisord.conf exists" && \
    echo "[VALIDATE 7/7] Checking allow_hidden config (root + devuser)..." && \
    grep -q 'allow_hidden.*True' /root/.jupyter/jupyter_notebook_config.py && \
    grep -q 'allow_hidden.*True' /home/devuser/.jupyter/jupyter_notebook_config.py && \
    echo "[OK] allow_hidden enabled in both jupyter configs" && \
    echo "" && \
    echo "[OK] All 7 validation checks passed" && \
    _NOW=$(date +%s) && \
    _ELAPSED=$((_NOW - _STAGE_START)) && \
    _START=$(grep '^START=' /tmp/.build-timer | cut -d= -f2) && \
    _TOTAL=$((_NOW - _START)) && \
    echo "L4=$_NOW" >> /tmp/.build-timer && \
    echo "[TIMER] Layer 4/5 (config+validation) took ${_ELAPSED}s | Cumulative: ${_TOTAL}s"

# ═══════════════════════════════════════════════════════════════════
# Layer 5/5: 最终元数据 + 清理 + 最终验证
# 变化频率：最低
# ═══════════════════════════════════════════════════════════════════
RUN echo "=== Layer 5/5: Final metadata, cleanup, and verification ===" && \
    _STAGE_START=$(date +%s) && \
    DEVUSER_UID=$(id -u devuser) && \
    echo "BUILD_DATE=$(date -u +%Y-%m-%dT%H:%M:%SZ)" > /etc/jupyter-podman-build-info && \
    echo "BASE_IMAGE=ubuntu:26.04" >> /etc/jupyter-podman-build-info && \
    echo "BUILD_TYPE=multistage-3stage" >> /etc/jupyter-podman-build-info && \
    echo "LOCALE=zh_CN.UTF-8" >> /etc/jupyter-podman-build-info && \
    echo "TIMEZONE=Asia/Shanghai" >> /etc/jupyter-podman-build-info && \
    echo "NON_ROOT_USER=devuser" >> /etc/jupyter-podman-build-info && \
    echo "NON_ROOT_UID=${DEVUSER_UID}" >> /etc/jupyter-podman-build-info && \
    echo "CONDA_DIR=/opt/conda" >> /etc/jupyter-podman-build-info && \
    echo "CONDA_DEFAULT_ENV=main" >> /etc/jupyter-podman-build-info && \
    echo "PYTHON_VERSION=${PYTHON_VERSION}" >> /etc/jupyter-podman-build-info && \
    echo "PYTHON_BUILD=${PYTHON_BUILD}" >> /etc/jupyter-podman-build-info && \
    echo "PODMAN_MODE=rootless" >> /etc/jupyter-podman-build-info && \
    echo "PODMAN_STORAGE_DRIVER=fuse-overlayfs" >> /etc/jupyter-podman-build-info && \
    echo "SERVICES=sshd,jupyter" >> /etc/jupyter-podman-build-info && \
    echo "SUPERVISOR=enabled" >> /etc/jupyter-podman-build-info && \
    echo "BUILD_TIMER=enabled" >> /etc/jupyter-podman-build-info && \
    cat /etc/jupyter-podman-build-info && \
    echo "[OK] Build info written to /etc/jupyter-podman-build-info" && \
    echo "[BUILD] Running final cleanup..." && \
    apt-get clean && \
    rm -rf /var/lib/apt/lists/* && \
    rm -rf /tmp/* /var/tmp/* && \
    echo "[OK] APT cache and /tmp cleaned" && \
    echo "" && \
    echo "┌─────────────────────────────────────────────────┐" && \
    echo "│  [FINAL VERIFICATION - Layer 5/5]               │" && \
    echo "│  Verifying all critical binaries are runnable   │" && \
    echo "└─────────────────────────────────────────────────┘" && \
    echo "[INFO] Final image size estimate (du -sh /): $(du -sh / 2>/dev/null | cut -f1 || echo 'N/A')" && \
    echo "[INFO] /opt/conda size: $(du -sh /opt/conda 2>/dev/null | cut -f1 || echo 'N/A')" && \
    echo "" && \
    tini --version >/dev/null 2>&1 && echo "[OK] tini (init) available" && \
    supervisord --version && echo "[OK] supervisord available" && \
    sshd -t && echo "[OK] sshd config valid" && \
    python --version && echo "[OK] python available (main env)" && \
    pip --version && echo "[OK] pip available" && \
    conda --version && echo "[OK] conda available" && \
    jupyter --version >/dev/null 2>&1 && echo "[OK] jupyter available" && \
    python -c "import omlmd; print('[OK] omlmd available (ML model OCI artifact)')" && \
    python -c "import olot; print('[OK] olot available (KServe ModelCar packager)')" && \
    test -x /usr/local/bin/olot_car.py && echo "[OK] olot_car.py helper script available" && \
    python -c "import subprocess, sys; from olot.backend.oras_py import is_oras_py; assert is_oras_py(), 'oras-py backend not available'; r = subprocess.run([sys.executable, '/usr/local/bin/olot_car.py', '--help'], capture_output=True, text=True); assert r.returncode == 0, r.stderr; assert 'pack' in r.stdout and 'extract' in r.stdout, 'pack/extract subcommands missing'; print('[OK] olot_car.py functional (olot + oras-py importable, pack/extract subcommands declared)')" && \
    test -d /run/host && echo "[OK] /run/host mount point exists (Toolbx compatibility)" && \
    test -f /run/.toolboxenv && echo "[OK] /run/.toolboxenv marker exists (Toolbx compatibility)" && \
    capsh --print >/dev/null 2>&1 && echo "[OK] capsh available (Toolbx capability boundary)" && \
    podman --version && echo "[OK] podman available" && \
    crun --version >/dev/null 2>&1 && echo "[OK] crun available" && \
    command -v pasta >/dev/null 2>&1 && echo "[OK] pasta available (rootless netns)" && \
    podman-compose --version && echo "[OK] podman-compose available (main env)" && \
    python -c "import podman; print('[OK] podman SDK (podman-py) importable (main env)')" && \
    toolbox --version && echo "[OK] toolbox available (guidance wrapper -> /usr/local/libexec/toolbox; version flag exits 0 without TOOLBOX_PATH)" && \
    test -x /usr/bin/flatpak-spawn && echo "[OK] flatpak-spawn available (Toolbx host callback prerequisite; mirrors upstream images/ubuntu/26.04/Containerfile)" && \
    test "$(id -u devuser)" = "1000" && test "$(id -g devuser)" = "1000" && echo "[OK] devuser fixed at UID/GID 1000 (Toolbx host user alignment)" && \
    test "$(getent passwd 1000 | cut -d: -f1)" = "devuser" && echo "[OK] passwd entry for UID 1000 is devuser" && \
    ! getent passwd ubuntu >/dev/null 2>&1 && echo "[OK] stock ubuntu account absent (UID 1000 no longer ambiguous)" && \
    sh -c 'toolbox >/dev/null 2>/tmp/.toolbox-bare.err; test "$?" -eq 1' && \
    grep -q 'TOOLBOX_PATH is not set in this session' /tmp/.toolbox-bare.err && \
    rm -f /tmp/.toolbox-bare.err && \
    echo "[OK] bare 'toolbox' degrades gracefully (exit 1 + guidance text instead of raw upstream error)" && \
    bash -n /usr/local/bin/entrypoint.sh && echo "[OK] entrypoint.sh syntax valid" && \
    bash -n /usr/local/bin/healthcheck.sh && echo "[OK] healthcheck.sh syntax valid" && \
    python -c "import sys, sysconfig; assert sysconfig.get_config_var('Py_GIL_DISABLED') == 1 and not sys._is_gil_enabled(); print('[OK] Python free-threading verified at final checkpoint (cp314t, GIL disabled)')" && \
    echo "" && \
    _NOW=$(date +%s) && \
    _ELAPSED=$((_NOW - _STAGE_START)) && \
    _FINAL_START=$(grep '^FINAL_START=' /tmp/.build-timer | cut -d= -f2) && \
    _L2=$(grep '^L2=' /tmp/.build-timer | cut -d= -f2) && \
    _L3=$(grep '^L3=' /tmp/.build-timer | cut -d= -f2) && \
    _L4=$(grep '^L4=' /tmp/.build-timer | cut -d= -f2) && \
    _T2=$((_L2 - _FINAL_START)) && \
    _T3=$((_L3 - _L2)) && \
    _T4=$((_L4 - _L3)) && \
    _T5=$_ELAPSED && \
    _TOTAL=$((_NOW - _FINAL_START)) && \
    echo "╔══════════════════════════════════════════════════════════════╗" && \
    echo "║      BUILD TIMING SUMMARY (3-Stage Multistage Build)        ║" && \
    echo "╠══════════════════════════════════════════════════════════════╣" && \
    printf "║  Final Stage (inherited from base-runtime)   (cached)      ║\n" && \
    printf "║  Layer 2/5  COPY conda + toolbox                    %4ds     ║\n" $_T2 && \
    printf "║  Layer 3/5  user+subuid+podman-config             %4ds     ║\n" $_T3 && \
    printf "║  Layer 4/5  configs+syntax validation             %4ds     ║\n" $_T4 && \
    printf "║  Layer 5/5  metadata+final verify                 %4ds     ║\n" $_T5 && \
    echo "╠══════════════════════════════════════════════════════════════╣" && \
    printf "║  FINAL STAGE TOTAL                               %4ds     ║\n" $_TOTAL && \
    echo "╚══════════════════════════════════════════════════════════════╝" && \
    echo "" && \
    echo "[INFO] Runtime chain: base-runtime (system) → conda-builder (build /opt/conda + podman-py/podman-compose) → final (runtime assembly)" && \
    echo "[INFO] Aux stage: toolbox-builder (golang:1.26-bookworm) → /usr/local/libexec/toolbox via COPY --from (not in final)" && \
    echo "[INFO] /usr/local/bin/toolbox is the guidance wrapper (Layer 4/5); it execs the real binary when TOOLBOX_PATH is set" && \
    echo "[INFO] Build tools (curl/wget/binutils/Go toolchain) are NOT in final image (isolated in conda-builder / toolbox-builder stages)" && \
    rm -f /tmp/.build-timer && \
    echo "[BUILD] ========== BUILD COMPLETE (multistage: 3-stage chain + toolbox-builder aux stage) ==========" && \
    echo ""

# ═══════════════════════════════════════════════════════════════════
# 运行时声明（不产生镜像层，仅元数据）
# ═══════════════════════════════════════════════════════════════════
WORKDIR /workspace
VOLUME ["/workspace"]
EXPOSE 22 8888

HEALTHCHECK --interval=30s --timeout=10s --start-period=45s --retries=3 \
    CMD /usr/local/bin/healthcheck.sh

ENTRYPOINT ["/usr/bin/tini", "--", "/usr/local/bin/entrypoint.sh"]
CMD []
