"""Compare the byte stream and allocation of locally generated regular files."""
import argparse
import errno
import hashlib
import json
import os
import platform
import shutil
import subprocess
import sys
import tempfile
from pathlib import Path

MIB = 1024 * 1024
LARGE = 64 * MIB
SMALL = 8 * MIB


def sync(file):
    file.flush()
    os.fsync(file.fileno())


def write_markers(path, length, resize_first=False):
    with path.open("xb") as file:
        if resize_first:
            file.truncate(length)
        file.write(b"HEAD")
        file.seek(length - 4)
        file.write(b"TAIL")
        sync(file)


def seek(file, offset, kind):
    try:
        return os.lseek(file.fileno(), offset, kind)
    except OSError as error:
        if error.errno == errno.ENXIO:
            return None
        raise


def measure(path):
    info = path.stat()
    digest = hashlib.sha256()
    with path.open("rb", buffering=0) as file:
        if hasattr(os, "SEEK_HOLE") and hasattr(os, "SEEK_DATA"):
            try:
                positions = {
                    "first_hole_from_start": seek(file, 0, os.SEEK_HOLE),
                    "first_data_from_middle": seek(file, info.st_size // 2, os.SEEK_DATA),
                }
            except OSError as error:
                if error.errno not in (errno.EINVAL, errno.ENOTSUP, errno.ENOSYS):
                    raise
                positions = {"unsupported": errno.errorcode[error.errno]}
        else:
            positions = {"unsupported": "missing SEEK_HOLE/SEEK_DATA"}
        file.seek(info.st_size // 2)
        assert file.read(4) == bytes(4)
        file.seek(0)
        for chunk in iter(lambda: file.read(MIB), b""):
            digest.update(chunk)
    record = {"logical_bytes": info.st_size, "st_blocks": info.st_blocks,
              "reported_allocated_bytes": info.st_blocks * 512,
              "sha256": digest.hexdigest(), "seek_offsets_bytes": positions}
    if sys.platform == "darwin":
        stat = subprocess.check_output(["stat", "-f", "%z %b", path], text=True).split()
        du = subprocess.check_output(["du", "-k", path], text=True).split()[0]
        assert list(map(int, stat)) == [info.st_size, info.st_blocks]
        record["du_kib"] = int(du)
    return record


def copy_skipping_zero_chunks(source, destination):
    with source.open("rb") as original, destination.open("xb") as target:
        for chunk in iter(lambda: original.read(MIB), b""):
            if chunk.count(0) == len(chunk):
                target.seek(len(chunk), os.SEEK_CUR)
            else:
                target.write(chunk)
        target.truncate(original.tell())
        sync(target)


def run(parent):
    with tempfile.TemporaryDirectory(dir=parent, prefix="sparse-lab-") as temporary:
        base = Path(temporary)
        sparse, dense = base / "seek-write", base / "stream-copy"
        write_markers(sparse, LARGE)
        with sparse.open("rb") as source, dense.open("xb") as target:
            shutil.copyfileobj(source, target, length=MIB)
            sync(target)
        sparse_row, dense_row = measure(sparse), measure(dense)
        assert sparse_row["sha256"] == dense_row["sha256"]
        rebuilt = base / "skip-zero-copy"
        copy_skipping_zero_chunks(dense, rebuilt)
        rebuilt_row = measure(rebuilt)
        assert rebuilt_row["sha256"] == dense_row["sha256"]
        assert rebuilt_row["logical_bytes"] == dense_row["logical_bytes"]
        with sparse.open("r+b") as file:
            file.seek(LARGE // 2)
            file.write(bytes(16 * 1024))
            sync(file)
        zero_row = measure(sparse)
        assert zero_row["sha256"] == sparse_row["sha256"]
        small, resized = base / "small-seek", base / "small-resize-first"
        write_markers(small, SMALL)
        write_markers(resized, SMALL, resize_first=True)
        small_row, resized_row = measure(small), measure(resized)
        assert small_row["sha256"] == resized_row["sha256"]

        blank = base / "resize-only"
        with blank.open("xb") as file:
            file.truncate(SMALL)
            sync(file)
        blank_row = measure(blank)
        assert blank_row["sha256"] == hashlib.sha256(bytes(SMALL)).hexdigest()
        blank_copy = base / "resize-only-copy"
        copy_skipping_zero_chunks(blank, blank_copy)
        blank_copy_row = measure(blank_copy)
        assert blank_copy_row["logical_bytes"] == blank_row["logical_bytes"]
        assert blank_copy_row["sha256"] == blank_row["sha256"]
        return {
            "environment": {"os": platform.system(), "os_version": platform.mac_ver()[0] or platform.release(),
                            "machine": platform.machine(), "python": sys.version.split()[0]},
            "large_seek_write": sparse_row, "large_sequential_copy": dense_row,
            "large_after_explicit_zero_write": zero_row, "small_seek_write": small_row,
            "small_resize_then_write": resized_row, "small_resize_only": blank_row,
            "large_rebuilt_skipping_zeros": rebuilt_row, "blank_rebuilt_skipping_zeros": blank_copy_row,
        }


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--dir", type=Path, default=Path.cwd(), help="parent of the temporary test directory")
    args = parser.parse_args()
    print(json.dumps(run(args.dir), indent=2))
