#!/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"
config="$repo/artifacts/c600-init.ipucfg"

cd "$repo"
make sdk_host_tensor_oracle popef_to_ipu_image direct_ipu_loader
(
  cd "$work"
  "$repo/sdk_host_tensor_oracle"
)
./popef_to_ipu_image "$work/sdk_host_tensor.popef" \
  "$work/sdk_host_tensor.ipuimg"

for run in 1 2; do
  input="$work/input-$run.bin"
  output="$work/output-$run.bin"
  head -c 64 /dev/urandom >"$input"
  ./direct_ipu_loader host-exchange "$work/sdk_host_tensor.ipuimg" \
    "$bootloader" "$config" "$repo/artifacts/sdk_host_tensor.ipuhsp" \
    source-write "$input" - \
    program-0 - - \
    destination-read - "$output"
  cmp "$input" "$output"
done

echo "direct host-exchange round trip: PASS"
