#!/usr/bin/env sh
# install.sh — GENERATED by pilot-app for io.pilot.duckdb 1.5.4.
# 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.duckdb 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" = "darwin" ] && [ "$ARCH" = "amd64" ]; then
  stage_one "https://pub-2328865fa11041b8a5efba00b940ec14.r2.dev/io.pilot.duckdb/1.5.4/darwin-amd64/duckdb-1.5.4-darwin-amd64.tar.gz" "4cf2355cda730299716a2480bebc040c24dfabfd258a80b3fc8d4b8a345c434d" "tar.gz" "duckdb-1.5.4-darwin-amd64/duckdb" "binary"
  echo "pilot-install: done"; exit 0
fi
if [ "$OS" = "darwin" ] && [ "$ARCH" = "arm64" ]; then
  stage_one "https://pub-2328865fa11041b8a5efba00b940ec14.r2.dev/io.pilot.duckdb/1.5.4/darwin-arm64/duckdb-1.5.4-darwin-arm64.tar.gz" "81f7634a4867868936cbb302ed4f5589c1024671e3e821346ba05dc9eae29461" "tar.gz" "duckdb-1.5.4-darwin-arm64/duckdb" "binary"
  echo "pilot-install: done"; exit 0
fi
if [ "$OS" = "linux" ] && [ "$ARCH" = "amd64" ]; then
  stage_one "https://pub-2328865fa11041b8a5efba00b940ec14.r2.dev/io.pilot.duckdb/1.5.4/linux-amd64/duckdb-1.5.4-linux-amd64.tar.gz" "a2a28a28feaf4a28f9c7c082fd042174b673755a73db561de01f46d56d151e9f" "tar.gz" "duckdb-1.5.4-linux-amd64/duckdb" "binary"
  echo "pilot-install: done"; exit 0
fi
if [ "$OS" = "linux" ] && [ "$ARCH" = "arm64" ]; then
  stage_one "https://pub-2328865fa11041b8a5efba00b940ec14.r2.dev/io.pilot.duckdb/1.5.4/linux-arm64/duckdb-1.5.4-linux-arm64.tar.gz" "a92ffbb1145dedf9dc5736001f26e42e2609b226ef02287c02e2f519dcd7e172" "tar.gz" "duckdb-1.5.4-linux-arm64/duckdb" "binary"
  echo "pilot-install: done"; exit 0
fi
echo "pilot-install: no artifact for ${OS}/${ARCH}" >&2; exit 1
