#!/bin/bash

# Script to run presubmit checks. Devs can run this script locally before sending out PRs for review to ensure
# CI is passing for their PR.

set -e
cd "$(dirname "$0")/.."

FMT_COMMAND="cargo fmt"
echo "Running $FMT_COMMAND..."
set -e
EXIT_CODE=0
$FMT_COMMAND -- --check || EXIT_CODE=$?
if [[ $EXIT_CODE -ne 0 ]]; then
    echo 'Run `'"$FMT_COMMAND"'` to fix.'
    exit $EXIT_CODE
fi

echo "Cargo fmt succeeded..."

echo "Running clippy..."
# Exclude warp_completer because we run clippy on it with default features (rather than all features) below.
#
# TODO(vorporeal): Re-enable the `all-features` flag once we've fixed things.
cargo clippy --workspace --exclude warp_completer --all-targets --tests -- -D warnings
# Run clippy on warp_completer with default, rather than all features enabled, because there is
# feature-gated logic for the WIP completions-on-js implementation.
cargo clippy -p warp_completer --all-targets --tests -- -D warnings
echo "clippy succeeded..."

echo "Running clang-format..."
./script/run-clang-format.py -r --extensions 'c,h,cpp,m' ./crates/warpui/src/ ./app/src/
echo "clang-format succeeded..."

echo "Running wgslfmt..."
# Normally a recursive glob pattern will do the trick, e.g. **/*.wgsl
# However, the default bash version in MacOS is too old to support that, so we use `find` instead.
find . -name "*.wgsl" -exec wgslfmt --check {} +
echo "wgslfmt succeeded..."

# check to see if we can run powershell on the device
if command -v pwsh /dev/null 2>&1; then
    echo "Running PSScriptAnalyzer..."
    ./script/lint_powershell -ci
    echo "PsScriptAnalyzer succeeded..."
elif [ "${GITHUB_ACTIONS}" == "true" ]; then
    # If we are in CI, and fail to find powershell, we should automatically fail
    echo "No powershell installation detected! Aborting!"
    exit 1
else
    # Otherwise, post a notice that we are skipping powershell
    echo "No Powershell detected! skipping PSScriptAnalyzer!"
fi

echo "Running tests via nextest..."
cargo nextest run --no-fail-fast --workspace --exclude command-signatures-v2
# Run warp_completer tests with the "v2" (completions-on-js) flag enabled. We do this to ensure that
# the v2 completions implementation doesn't regress/rot while it's development is paused.
cargo nextest run -p warp_completer --features v2
echo "Running doc tests..."
cargo test --doc
echo "Tests succeeded..."

echo "Congrats! All presubmits checks passed."
