#!/usr/bin/env python3
import os
import json
import zlib
import time

CACHE_DIR = "/var/www/cdn/files"
OUTPUT = "/var/www/cdn/hash.json"

def file_hash(path):
    crc = 0
    with open(path, "rb") as f:
        while True:
            chunk = f.read(8192)
            if not chunk:
                break
            crc = zlib.crc32(chunk, crc)
    return str(crc & 0xFFFFFFFF)

def main():
    result = []
    date_value = int(time.time())

    for root, dirs, files in os.walk(CACHE_DIR):
        for name in files:
            full_path = os.path.join(root, name)
            rel_path = os.path.relpath(full_path, CACHE_DIR).replace("\\", "/")
            path = "files/" + rel_path

            try:
                size = os.path.getsize(full_path)
                file_hash_value = file_hash(full_path)

                result.append({
                    "date": date_value,
                    "hash": file_hash_value,
                    "name": name,
                    "path": path,
                    "size": size
                })
                print(f"OK: {path}")
            except Exception as e:
                print(f"ERROR: {path} -> {e}")

    with open(OUTPUT, "w", encoding="utf-8") as f:
        json.dump(result, f, ensure_ascii=False, indent=2)

    print(f"\nГотово: {OUTPUT}")
    print(f"Файлов: {len(result)}")

if __name__ == "__main__":
    main()