#!/usr/bin/env bash

# Parse command line arguments.
set -euo pipefail
eval "$(claptrap --spec - -- "$@" <<SPEC
name: test.sh
args:
  args:
    num-args: 0..
    help: Positional arguments
  windows:
    short: w
    long: windows
    action: set-true
    help: Build for Windows
  strict:
    short: s
    long: strict
    action: set-true
    help: Warnings as errors
  quiet:
    short: q
    long: quiet
    action: set-true
    help: Quiet log messages
SPEC
)"

# Set up local environment.
target=''
quiet=''
test "$claptrap_windows" = 'true' && target='--target=x86_64-pc-windows-gnu --no-run'
test "$claptrap_strict" = 'true' && export RUSTFLAGS='-D warnings'
test "$claptrap_quiet" = 'true' && quiet='--quiet'

# Build Rust test target.
output=$(mktemp)
cargo test $target $quiet --release --lib --color=always "${claptrap_args[@]}" 2>&1 | tee "$output" || exit

# Run Windows test target in Wine.
if test "$claptrap_windows" = 'true'; then
  exec=$(egrep '\bExecutable\b.+\bunittests\b' "$output" | egrep -o '\((\S+)\)')
  if test -n "$exec"; then
    exec="${exec:1:-1}"
    wine "$exec" $quiet "${claptrap_args[@]}"
  fi
fi

# Clean up temporary file.
rm -rf "$output"
