#!/usr/bin/env sh
# Package the adapter.spt release asset (HOST-PLAN.md D2), ground-truthed
# against the public docs (harness-contract/manifest): `spt adapter add
# --release` extracts the archive into the adapter's install dir, and a
# [session] command's bare first token resolves as `<install_dir>/<program>`
# (+ `.exe` on Windows) before PATH — NO per-triple subdirectories. So the
# binary sits at the ARCHIVE ROOT beside manifest.toml. (A bin/<triple>/
# layout was tried first and the spawn failed with os error 2 — v1.0.0.)
#
# One archive therefore carries ONE platform's binary. Windows-x86_64 is the
# only released platform today; more platforms mean per-OS release assets
# (adapter-<os>-<arch>.spt + `spt adapter add --asset`), not a fat archive —
# `spt-mobile-host` (linux) and `spt-mobile-host` (darwin) would collide at
# the root.
#
#   ci/package-adapter.sh [out-dir]     # default out-dir: dist/
#
# [impl->REQ-HOST-ADAPTER]
set -eu

repo_root=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
out_dir=${1:-"$repo_root/dist"}
stage="$out_dir/adapter-stage"

host_triple=$(rustc -vV | sed -n 's/^host: //p')
case "$host_triple" in
  *windows*) exe=".exe" ;;
  *) exe="" ;;
esac

echo "building spt-mobile-host (release, $host_triple)"
cargo build --release --manifest-path "$repo_root/host/Cargo.toml"

rm -rf "$stage"
mkdir -p "$stage"
cp "$repo_root/host/manifest.toml" "$stage/manifest.toml"
cp "$repo_root/host/target/release/spt-mobile-host$exe" "$stage/"

# Tar from inside the stage so the archive ROOT holds manifest.toml + binary
# (the contract `spt adapter add --release` unpacks against).
(cd "$stage" && tar -cf "$out_dir/adapter.spt" manifest.toml "spt-mobile-host$exe")
echo "packaged: $out_dir/adapter.spt"
tar -tf "$out_dir/adapter.spt"
