import hashlib
import os
import shutil
import tempfile

import requests


def download_check_hash(url, hash_digest, final_path, hash_cls=hashlib.sha512):
    fh, temp_path = tempfile.mkstemp()
    try:
        new_hash = hash_cls()
        with requests.get(url, stream=True) as r:
            r.raise_for_status()
            with open(temp_path, "wb") as f:
                for chunk in r.iter_content(chunk_size=8192):
                    new_hash.update(chunk)
                    f.write(chunk)
        assert new_hash.hexdigest() == hash_digest
        shutil.copy(temp_path, final_path)
    finally:
        os.close(fh)
        os.unlink(temp_path)
