#!/bin/bash
# shellcheck disable=SC2046
set -euo pipefail
IFS=$'\n\t'
cd "$(dirname "$0")"/..

# Usage:
#    ./tools/spell-check.sh

metadata=$(cargo metadata --format-version=1 --all-features --no-deps)
dependencies=''
for id in $(jq <<<"${metadata}" '.workspace_members[]'); do
    dependencies+=$'\n'
    dependencies+=$(jq <<<"${metadata}" ".packages[] | select(.id == ${id})" | jq -r '.dependencies[].name')
done
cat >.github/.cspell/rust-dependencies.txt <<EOF
// This file is @generated by $(basename "$0").
// It is not intended for manual editing.

EOF
# shellcheck disable=SC2001
sed <<<"${dependencies}" 's/[0-9_-]/\n/g' | LC_ALL=C sort -f -u | (grep -E '.{4,}' || true) >>.github/.cspell/rust-dependencies.txt

npx cspell --no-progress $(git ls-files)

# Check duplications in dictionary
for dictionary in .github/.cspell/*.txt; do
    if [[ "${dictionary}" == .github/.cspell/project-dictionary.txt ]]; then
        continue
    fi
    dup=$(sed '/^$/d' .github/.cspell/project-dictionary.txt "${dictionary}" | LC_ALL=C sort -f | uniq -d -i | (grep -v '//.*' || true))
    if [[ -n "${dup}" ]]; then
        echo "error: duplicated words in dictionaries; please remove the following words from .github/.cspell/project-dictionary.txt"
        echo "======================================="
        echo "${dup}"
        echo "======================================="
    fi
done

# Fail CI if .github/.cspell/rust-dependencies.txt needs to be updated.
if [[ -n "${CI:-}" ]]; then
    if ! git --no-pager diff --exit-code .github/.cspell/rust-dependencies.txt; then
        echo "error: please update .github/.cspell/rust-dependencies.txt"
    fi
fi
