#!/usr/bin/env bash

set -euo pipefail
# Find all tracked .go files, excluding test files and files in tools/ or test/
all_files=$(git ls-files | grep -E '\.go$' | grep -vE '_test\.go$' | grep -vE '^tools/' | grep -vE '^test/')

found_error=false

# Regex: starts with wg, then any number of non-space, non-linebreak chars, then .Done()
pattern='wg[^[:space:]]*\.Done\(\)'
# Exclude: defer or // followed by any amount of letters, spaces, or dots, then wg...Done()
exclude='(defer|//)[[:space:].a-zA-Z]*wg[^[:space:]]*\.Done\(\)'
# Exclude: lines ending with //nolint:SA2000 - there is a staticcheck linter for wg.Done(), but I couldn't figure out how to enable it
nolint_exclude='//nolint:SA2000$'

excluded_files=(
    "adapters/handlers/rest/server.go"           # autogenerated
)


for file in $all_files; do
      if [[ " ${excluded_files[@]} " =~ " ${file} " ]]; then
          continue
      fi

    # Use grep -nE to get line numbers and matching lines, then exclude lines with defer or // before wg...Done()
    # and lines ending with //nolint:SA2000
    matches=$(grep -nE "$pattern" "$file" | grep -vE "$exclude" | grep -vE "$nolint_exclude" || true)
    if [[ -n "$matches" ]]; then
        while IFS= read -r match; do
            lineno=$(echo "$match" | cut -d: -f1)
            line=$(echo "$match" | cut -d: -f2-)
            echo "Error: $file:$lineno: $line" >&2
        done <<< "$matches"
        found_error=true
    fi

done

if [[ "$found_error" = true ]]; then
    exit 1
fi
