#!/usr/bin/env python3

# Splits one explicitly named hash file into individual .hash files.
# Rewrites each .hash file with the standard header.

import sys
import re
import shutil
import ctypes
from pathlib import Path

# Standard checksum file header template:
CORZ_HEADER = (
    "# made with checksum.. point-and-click hashing for windows.\n"
    "# from corz.org.. http://corz.org/windows/software/checksum/\n"
    "#\n"
)

# Matches metadata line format: #algo#filename#timestamp
META_PATTERN = re.compile(r"^#([a-zA-Z0-9_-]+)#(.+)#([^#]+)$")


def copy_file_attributes(src: Path, dst: Path) -> None:
    """Copies timestamps, stat bits, and exact Windows file attributes (Hidden, ReadOnly, System, etc.)."""
    # Copy file creation/modification timestamps and basic permissions
    shutil.copystat(src, dst)

    # Query and apply native Windows file attributes directly from the source file
    if sys.platform == "win32":
        attrs = ctypes.windll.kernel32.GetFileAttributesW(str(src))
        if attrs != -1:
            ctypes.windll.kernel32.SetFileAttributesW(str(dst), attrs)


def split_hash_file(file_path: str) -> None:
    source_path = Path(file_path)
    if not source_path.is_file():
        print(f"Error: File '{file_path}' not found.")
        sys.exit(1)

    output_dir = source_path.parent

    with open(source_path, "r", encoding="utf-8", errors="ignore") as f:
        lines = f.readlines()

    current_meta_line = None
    current_filename = None
    count = 0

    for line in lines:
        line_str = line.strip()
        if not line_str:
            continue

        meta_match = META_PATTERN.match(line_str)
        if meta_match:
            current_meta_line = line_str
            current_filename = meta_match.group(2)
            continue

        # Process checksum data line associated with the metadata
        if current_meta_line and current_filename and (" " in line_str or "\t" in line_str):
            hash_line = line_str

            stem = Path(current_filename).stem
            out_filepath = output_dir / f"{stem}.hash"

            content = (
                f"{CORZ_HEADER}"
                f"{current_meta_line}\n"
                f"{hash_line}\n"
            )

            with open(out_filepath, "w", encoding="utf-8") as out_f:
                out_f.write(content)

            # Inherit exact attributes and timestamps from the original hash file
            copy_file_attributes(source_path, out_filepath)

            count += 1
            print(f"Created: {out_filepath.name}")

            current_meta_line = None
            current_filename = None

    print(f"\nCompleted. Generated {count} individual hash file(s).")


if __name__ == "__main__":
    if len(sys.argv) < 2:
        print("Usage: python split_hashes.py <path_to_hash_file>")
        sys.exit(1)

    split_hash_file(sys.argv[1])
