#!/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
tile=100

cd "$repo"
make sdk_host_exchange_d2h_redirect_oracle popef_to_ipu_image ipu_image \
  direct_ipu_loader
./sdk_host_exchange_d2h_redirect_oracle "$tile" "$work/oracle.popef" \
  "$work/expected.bin"
./popef_to_ipu_image "$work/oracle.popef" "$work/oracle.ipuimg"
./ipu_image redirect-d2h-source "$work/oracle.ipuimg" \
  "$work/redirected.ipuimg" "$tile" 64

cat >"$work/protocol.ipuhsp" <<'EOF'
IPU-HOST-EXCHANGE 1
startup-mark 23
page 0 4096
page 1 4096
attach 1
attach 0
command 1 0
call write-first 2 4
input write-first 0 64 0 64
call read 1 4
output read 0 64 0 64
EOF

head -c 64 /dev/urandom >"$work/first.bin"
./direct_ipu_loader host-exchange "$work/redirected.ipuimg" \
  "$POPLAR_SDK_ENABLED/bin/ipu/tile_bootloader_ipu2.elf" \
  artifacts/c600-init.ipucfg "$work/protocol.ipuhsp" \
  write-first "$work/first.bin" - read - "$work/output.bin"
if ! cmp -s "$work/expected.bin" "$work/output.bin"; then
  if cmp -s "$work/first.bin" "$work/output.bin"; then
    echo "D2H returned the unredirected first source" >&2
  elif cmp -s <(head -c 64 /dev/zero) "$work/output.bin"; then
    echo "D2H returned an all-zero source" >&2
  else
    echo "D2H returned data matching neither uploaded source" >&2
  fi
  exit 1
fi
echo "independently redirected arbitrary-tile D2H source: PASS"
