# syntax=docker/dockerfile:1.6
FROM --platform=$TARGETPLATFORM ubuntu:24.04

ARG TARGETARCH
ARG SUI_REF=mainnet-v1.53.2

# minimal tools + jq + age (optional lock/unlock helpers)
RUN apt-get update && \
    apt-get install -y --no-install-recommends ca-certificates curl jq tar age && \
    rm -rf /var/lib/apt/lists/*

# Fetch the right prebuilt tarball for this arch and install 'sui'
RUN set -eux; \
  case "$TARGETARCH" in \
    amd64) want='(x86_64|amd64)' ;; \
    arm64) want='(aarch64|arm64)' ;; \
    *) echo "unsupported arch: $TARGETARCH" >&2; exit 1 ;; \
  esac; \
  api="https://api.github.com/repos/MystenLabs/sui/releases/tags/${SUI_REF}"; \
  url="$(curl -fsSL --http1.1 --retry 5 --retry-connrefused --retry-delay 2 "$api" \
          | jq -r --arg want "$want" '.assets[] | select(.name|test("ubuntu.*" + $want)) | .browser_download_url' \
          | head -n1)"; \
  test -n "$url"; \
  echo "Downloading: $url"; \
  curl -fL --http1.1 --retry 5 --retry-connrefused --retry-delay 2 -o /tmp/sui.tgz "$url"; \
  mkdir -p /opt/sui; \
  tar -xzf /tmp/sui.tgz -C /opt/sui; \
  # find and install the 'sui' binary from the extracted tree
  f="$(find /opt/sui -type f -name sui -perm -u+x | head -n1)"; \
  test -n "$f"; install -m 0755 "$f" /usr/local/bin/sui; \
  # sanity check in the image
  /usr/local/bin/sui --version

# runtime user and homedir setup
RUN set -eux; \
    uid=1000; gid=1000; \
    gname="$(getent group "$gid" | cut -d: -f1 || true)"; \
    if [ -z "$gname" ]; then \
      groupadd -g "$gid" sui; \
      gname=sui; \
    fi; \
    if getent passwd "$uid" >/dev/null; then \
      # UID 1000 already exists; create 'sui' with next available UID but keep primary group = gid 1000
      useradd -m -g "$gid" sui; \
    else \
      useradd -m -u "$uid" -g "$gid" sui; \
    fi; \
    install -d -m 0770 -o sui -g "$gid" /home/sui/.sui/sui_config

USER sui
WORKDIR /home/sui

# keep the container ready to be exec'd into by your scripts
CMD ["/bin/sh","-lc","sleep infinity"]
