#!/usr/bin/env python3
# NB: get aiofiles yeah?
import pathlib
import os
import time
import sys

def in_content(needle: str, pathlike: str):
    content = ""
    try:
        # NB: latin-1 since we actually do have some language translation files
        with open(pathlike, 'r', encoding='latin-1') as f:
            content = f.read().lower()
    except BaseException as e:
        raise BaseException(f"Unable to determine content of {pathlike}: {e}") from e

    return needle in content

def gitignore_patterns(gitignore_f: str | None = None):
    with open(gitignore_f, 'r') as f:
        return {line for line in (line.strip() for line in f) if not line.startswith('#') and line}

def main():
    begin_stopwatch_s = time.perf_counter()
    # if OSError, too bad, user probably knows why, so just throw xD
    username = os.getlogin() 
    ignore_patterns = gitignore_patterns(os.getenv("IGNORE_FILE", ".gitignore"))
    ignore_patterns.add(".git")
    print(f"{ignore_patterns=}")

    # NB: impure pattern due to walk being costly
    username_in_file = []
    username_in_content = []
    user_lower = username.lower()

    for root, dirs, filenames in pathlib.Path("./").walk():
        absdirs = [
            e 
            for e in ((root.joinpath(d), d) for d in dirs)
            if all(not e[0].match(pat) for pat in ignore_patterns)
        ]
        files = [
            e 
            for e in ((root.joinpath(f), f) for f in filenames)
            if all(not e[0].match(pat) for pat in ignore_patterns)
        ]

        username_in_file.extend(
            abspath
            for abspath, fname in absdirs + files 
            if user_lower in fname.lower()
        )
        username_in_content.extend(
            absfname
            for absfname, _ in files
            if in_content(user_lower, absfname)
        )
        print(f"Checked batch {[rel for _, rel in files + absdirs]} in {root}", file=sys.stderr)


    nl = "\n"
    if username_in_file != []:
        print(f"Doxxed by username in file path:\n{nl.join(f'- {e}' for e in username_in_file)}")
    if username_in_content != []:
        print(f"Doxxed by username in file content:\n{nl.join(f'- {e}' for e in username_in_content)}")

    stop_stopwatch_s = time.perf_counter()
    print(f"done analyzing in {(stop_stopwatch_s - begin_stopwatch_s):.04}s")

if __name__ == "__main__":
    main()
