import hashlib
import logging
import os

from defence360agent.utils import file_hash_and_size

logger = logging.getLogger(__name__)


def migrate(migrator, database, fake=False, **kwargs):
    MalwareHit = migrator.orm["malware_hits"]
    try:
        for hit in MalwareHit.select():
            path = hit.orig_file.encode("utf-8", errors="surrogateescape")
            try:
                st = os.stat(path)
            except FileNotFoundError:
                logger.warning(
                    "Malware file %s does not exist, skipping", path
                )
                continue

            if hit.mode is not None and not hit.restored:
                os.chown(path, 0, 0)
                hit.uid, hit.gid = st.st_uid, st.st_gid

            hit.hash, hit.size = file_hash_and_size(path, hashlib.sha256)
            hit.save()
    except Exception as e:
        logger.exception(e)


def rollback(migrator, database, fake=False, **kwargs):
    pass
