#! .venv/bin/python
import subprocess
import sys

from detect_secrets.pre_commit_hook import main as find_secrets


TRACKED_CHANGES = ["git", "diff", "HEAD", "--name-only"]
STAGED_CHANGES = ["git", "diff", "--cached", "--name-only"]
UNTRACKED_CHANGES = ["git", "ls-files", "--others", "--exclude-standard"]


def git_file_list(cmd):
    comproc = subprocess.run(cmd, capture_output=True)
    return [f.decode() for f in comproc.stdout.split()]


def git_staged_files():
    return git_file_list(STAGED_CHANGES)


def git_all_files():
    return git_file_list(TRACKED_CHANGES) + git_file_list(UNTRACKED_CHANGES)


def main(arg):
    """
    If `arg` is "staged", this will only check files that have been
    staged to the git index. Otherwise, it will check staged and
    unstaged files.
    """
    files = []
    if arg == "staged":
        files = git_staged_files()
    else:
        files = git_all_files()

    return find_secrets(["--baseline", ".secrets.baseline"] + files)


if __name__ == "__main__":
    arg = sys.argv[1] if len(sys.argv) > 1 else None
    print("Finished scanning for secrets")
    sys.exit(main(arg))
