#!/usr/bin/env python3

# FindLegacyHashes.py
# Hunt down all legacy hash files, for upgrading. In case any were missed.

# 100% AI Generated code.

import os
import re
from pathlib import Path

# Configuration
SEARCH_DIR = r"."
REPORT_FILE = r"legacy_hash_report.txt"
HASH_EXTENSIONS = {".checksum", ".hash", ".md5", ".sfv", ".sha1"}

# Regex matching exactly 32-character (MD5) or 40-character (SHA-1) hex strings
LEGACY_HASH_PATTERN = re.compile(r"\b([a-fA-F0-9]{32}|[a-fA-F0-9]{40})\b")


def scan_for_legacy_hashes(search_dir, extensions, report_path):

    report_lines = []
    total_matches = 0
    scanned_files = 0

    search_path = Path(search_dir).resolve()

    print(f"Scanning for legacy hashes..")

    for file_path in search_path.rglob("*"):
        if file_path.is_file() and file_path.suffix.lower() in extensions:
            scanned_files += 1
            file_matches = []

            try:
                with open(file_path, "r", encoding="utf-8", errors="ignore") as f:
                    for line_num, line in enumerate(f, start=1):
                        matches = LEGACY_HASH_PATTERN.findall(line)
                        for match in matches:
                            hash_type = "MD5 (32-char)" if len(match) == 32 else "SHA-1 (40-char)"
                            file_matches.append(f"  Line {line_num}: [{hash_type}] {match}")

            except Exception as err:
                file_matches.append(f"  ERROR reading file: {err}")

            if file_matches:
                total_matches += len(file_matches)
                report_lines.append(f"File: {file_path}")
                report_lines.extend(file_matches)
                report_lines.append("")

    with open(report_path, "w", encoding="utf-8") as report:
        report.write(f"Legacy Hash Scan Report\n")
        report.write(f"Root Directory: {search_path}\n")
        report.write(f"Files Scanned:  {scanned_files}\n")
        report.write(f"Matches Found:  {total_matches}\n")
        report.write("=" * 60 + "\n\n")

        if report_lines:
            report.write("\n".join(report_lines))
        else:
            report.write("No legacy 32 or 40 character hex hashes found.\n")

    print(f"Scan complete. {scanned_files} files checked, {total_matches} legacy hashes logged to '{report_path}'.")


if __name__ == "__main__":

    scan_for_legacy_hashes(SEARCH_DIR, HASH_EXTENSIONS, REPORT_FILE)
