#!/usr/bin/env bash
set -euo pipefail

: "${POPLAR_SDK_ENABLED:?source the Poplar SDK environment first}"

repo=$(cd "$(dirname "$0")/.." && pwd)
work=$(mktemp -d)
trap 'rm -rf "$work"' EXIT
bootloader="$POPLAR_SDK_ENABLED/bin/ipu/tile_bootloader_ipu2.elf"

cd "$repo"
make sdk_host_exchange_redirect_oracle popef_to_ipu_image ipu_image \
  host_exchange_plan_dump direct_ipu_loader
"$repo/sdk_host_exchange_redirect_oracle" "$work/redirect.popef"
"$repo/popef_to_ipu_image" "$work/redirect.popef" "$work/redirect.ipuimg"

# This fixture places the HostWrite target at 0x50120 and an adjacent buffer at
# 0x50160. Redirect the request header; the vertex copies only the latter.
read -r replacement ignored < <(
  "$repo/host_exchange_plan_dump" h2d 0 0x50160 0x40 64
)
"$repo/ipu_image" patch-word "$work/redirect.ipuimg" \
  "$work/patched.ipuimg" 0 0x501b8 0xec000209 "$replacement"

head -c 64 /dev/urandom >"$work/input.bin"
"$repo/direct_ipu_loader" host-exchange "$work/patched.ipuimg" \
  "$bootloader" "$repo/artifacts/c600-init.ipucfg" \
  "$repo/artifacts/sdk_host_tensor.ipuhsp" \
  source-write "$work/input.bin" - \
  program-0 - - \
  destination-read - "$work/output.bin"
cmp "$work/input.bin" "$work/output.bin"
echo "independent host-exchange packet encoding: PASS"
