#!/bin/bash

status=0

if [[ $(codespell --skip ./**/target,./**/build,./docs/*.js,./docs/*.json -I .codespellignore 2>&1) ]];
then
    echo "There are typos in some of the files you've changed. Please run the following to check what they are:"
    echo "codespell --skip ./**/target,./**/build,./docs/*.js,./docs/*.json -I .codespellignore"
    echo ""
    status=1
fi

# Run clang-format on CUDA, C, and CPP files
# clang-format writes to stderr in dry-run mode. In order to capture the output to detect if there are changes needed we redirect stderr to stdin
if [[ $(find ./ \( -path ./icicle/build -prune -o -path ./**/target -prune -o -path ./examples -prune \) -iname *.h -or -iname *.cuh -or -iname *.cu -or -iname *.c -or -iname *.cpp | xargs clang-format --dry-run -ferror-limit=1 -style=file 2>&1) ]];
then
    echo "🚨 There are files in Icicle Core that need formatting."
    echo ""
    echo "Please format all .c, .cpp, .h, .cu, .cuh files using the following command:"
    echo "find ./ \( -path ./icicle/build -prune -o -path ./**/target -prune -o -path ./examples -prune \) -iname *.h -or -iname *.cuh -or -iname *.cu -or -iname *.c -or -iname *.cpp | xargs clang-format -i -style=file"
    echo ""
    echo "If you only want to see what formatting is required please run:"
    echo "find ./ \( -path ./icicle/build -prune -o -path ./**/target -prune -o -path ./examples -prune \) -iname *.h -or -iname *.cuh -or -iname *.cu -or -iname *.c -or -iname *.cpp | xargs clang-format --dry-run -style=file"
    echo ""
    status=1
fi

# Run go fmt across all Golang packages
if [[ $(go list ./... | xargs go fmt) ]];
then
    echo "🚨 There are Golang files that need formatting."
    echo "Please commit the formatted files"
    echo ""
    status=1
fi

# Run cargo fmt on Rust files
cd wrappers/rust
if [[ $(find . -path ./icicle-curves/icicle-curve-template -prune -o -name target -prune -o -iname *.rs -print | xargs cargo fmt --check --) ]];
then
    echo "🚨 There are Rust files that need formatting."
    echo "Please go to wrappers/rust and format the Rust files using the following command:"
    echo "find . -path ./icicle-curves/icicle-curve-template -prune -o -name target -prune -o -iname *.rs -print | xargs cargo fmt --check --"
    status=1
fi

exit $status