"""The edx_lint check command."""

import os
import re

from edx_lint.metadata import existing_known_files
from edx_lint.tamper_evident import TamperEvidentFile


def check_main(argv):
    """
    check [FILENAME ...]
        Check that FILENAME has not been edited since writing.
        If FILENAME is omitted, all existing files are checked.
    """
    if len(argv) >= 1:
        filenames = argv
    else:
        filenames = list(existing_known_files())

    ret = 0

    for filename in filenames:
        if os.path.exists(filename):
            tef = TamperEvidentFile(filename)
            if tef.validate():
                print(f"{filename} is good")
            else:
                with open(filename, encoding="utf-8") as f:
                    text = f.read()
                if re.search(r"generated by edx[-_]lint", text):
                    print(f"{filename} seems to have been edited")
                    ret = 1
                else:
                    print(f"{filename} wasn't written by edx_lint")
        else:
            print(f"{filename} doesn't exist")
            ret = 2

    return ret
