#!/usr/bin/env bash
# Run the ragger functional tests against speculos, in Docker.
#
# Speculos does not run natively on macOS, so both it and ragger live in a
# container built from Ledger's dev-tools image (see tests/Dockerfile). The
# image is multi-arch, so this runs natively on Apple silicon.
#
# Usage:
#   ./scripts/test                 # stax
#   ./scripts/test flex            # another device
#   ./scripts/test stax --golden_run          # regenerate snapshots
#   ./scripts/test stax -k policy -v          # any extra pytest args
#
# Regenerating snapshots is a deliberate act: they are the record of what the
# review screen shows, which is the thing a hardware wallet is for. Look at the
# diff before committing one.
set -euo pipefail

cd "$(dirname "$0")/.."

DEVICE="${1:-stax}"
[[ $# -gt 0 ]] && shift

# ragger's device names differ from the build target directory names.
case "$DEVICE" in
  nanosp) TARGET=nanosplus ;;
  *)      TARGET="$DEVICE" ;;
esac

IMAGE=ledger-hns-test

if ! docker image inspect "$IMAGE" >/dev/null 2>&1; then
  echo "building $IMAGE (first run only)..."
  docker build -t "$IMAGE" -f tests/Dockerfile tests/
fi

if [[ ! -f "target/$TARGET/release/app-handshake" ]]; then
  echo "app not built for $TARGET, building..."
  ./scripts/build "$TARGET"
fi

exec docker run --rm -v "$PWD":/app -w /app "$IMAGE" \
  pytest tests/standalone --tb=short -v --device "$DEVICE" "$@"
