#!/bin/bash

set -euo pipefail

had_errors=

if [ -n "${RO_SRC_DIR+x}" ]; then
  echo "== Copying sources" >&2
  mkdir -p ./build
  cp -r "$RO_SRC_DIR"/Cargo.* "$RO_SRC_DIR"/src ./build
  cd ./build
fi

echo "== Install dependencies" >&2
rustup component add clippy rustfmt

if [ -e /etc/alpine-release ]; then
  echo "== Configuring Alpine Linux" >&2
  apk add musl-dev openssl-dev
  export RUSTFLAGS="-C target-feature=-crt-static"
fi

echo "== Running cargo test" >&2
if ! cargo test; then
  had_errors=1
fi

echo "== Running clippy" >&2
if ! cargo clippy; then
  had_errors=1
fi

echo "== Running rustfmt" >&2
if ! find src -type f -name '*.rs' | xargs rustfmt --edition 2021 --check; then
  had_errors=1
fi

if [ "$had_errors" ]; then
  echo "Failing checks" >&2
  exit 1
fi
