import os
import sys
from pathlib import Path

def grep(string, glob="*", path=".", recursive=True):
    """Return files in path that contain ``string``.

    Returns:
        List[Tuple[int, str]]: A list of matching files with the line
            number of the first match

    """
    assert glob, "glob pattern must be set"
    matches = []
    path = Path(path)
    if recursive:
        glob = f"**{os.sep}{glob}"
    for file in path.glob(glob):
        if not file.is_file():
            continue
        with open(file) as fp:
            try:
                for line_no, line in enumerate(fp, 1):
                    if string in line:
                        matches.append((line_no, str(file)))
                        break
            except UnicodeDecodeError:
                print(f"Could not decode {file}; skipping)", file=sys.stderr)
                continue
    return matches


if __name__ == "__main__":
    import sys
    _, string, glob, path = sys.argv
    matches = grep(string, glob, path)
    if matches:
        for match in matches:
            print(match)
        sys.exit(0)
    else:
        print("No matches found", file=sys.stderr)
        sys.exit(404)
