#!/usr/bin/env sh
# install.sh — GENERATED by pilot-app for io.pilot.docker 29.6.1.
# Fetches this app's artifacts from the Pilot R2 registry, verifies each
# sha256, stages them under $APP, and runs any install steps — in dependency
# order. This mirrors the adapter's built-in staging (internal/backend/stage.go);
# either is sufficient. Usage: APP=/path/to/app sh install.sh
set -eu

APP="${APP:-$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)}"
OS="$(uname -s | tr '[:upper:]' '[:lower:]')"
ARCH="$(uname -m)"
case "$ARCH" in aarch64) ARCH=arm64;; x86_64) ARCH=amd64;; esac
echo "pilot-install: staging io.pilot.docker artifacts for ${OS}/${ARCH} into ${APP}"

sha256_of() {
  if command -v sha256sum >/dev/null 2>&1; then sha256sum "$1" | awk '{print $1}';
  else shasum -a 256 "$1" | awk '{print $1}'; fi
}

stage_one() { # url sha unpack exec_path role
  url="$1"; want="$2"; unpack="$3"; exec_path="$4"; role="$5"
  tmp="$(mktemp)"
  echo "  fetch  $url"
  curl -fSL "$url" -o "$tmp"
  got="$(sha256_of "$tmp")"
  if [ "$got" != "$want" ]; then echo "  sha256 MISMATCH for $exec_path: want $want got $got" >&2; rm -f "$tmp"; exit 1; fi
  echo "  verify ok ($want)"
  if [ "$unpack" = "tar.gz" ]; then
    tar -xzf "$tmp" -C "$APP"; rm -f "$tmp"
  else
    dest="$APP/$exec_path"; mkdir -p "$(dirname -- "$dest")"; mv "$tmp" "$dest"
    if [ "$role" != "data" ]; then chmod 0755 "$dest"; fi
  fi
  echo "  staged $exec_path"
}

if [ "$OS" = "linux" ] && [ "$ARCH" = "amd64" ]; then
  stage_one "https://pub-2328865fa11041b8a5efba00b940ec14.r2.dev/io.pilot.docker/29.6.1/linux-amd64/docker-29.6.1-linux-amd64.tar.gz" "af67328c2d617401f22c108b2ebe5f06e6f59978c50a3f2c07d5f0041216172d" "tar.gz" "docker-29.6.1-linux-amd64/bin/dockerctl" "binary"
  echo "pilot-install: done"; exit 0
fi
if [ "$OS" = "linux" ] && [ "$ARCH" = "arm64" ]; then
  stage_one "https://pub-2328865fa11041b8a5efba00b940ec14.r2.dev/io.pilot.docker/29.6.1/linux-arm64/docker-29.6.1-linux-arm64.tar.gz" "c16db13a77f40fd9af7fe5520cb1bd9c78b5c2ab2d6e1749863683dce957f572" "tar.gz" "docker-29.6.1-linux-arm64/bin/dockerctl" "binary"
  echo "pilot-install: done"; exit 0
fi
echo "pilot-install: no artifact for ${OS}/${ARCH}" >&2; exit 1
