"""
Different operating systems have developed a convention to mark files that originate from other devices or the
internet to prevent accidentally executing them. Such can provide some additional security to the machine and
its owner.
This file contains platform specific utilities that implement such a feature. Some systems may hold extra information
about the file, but these are volatile. For example Windows deletes the mark data if a trust verification succeeds.
NOTE: Errors here are mostly completely ignored as the usability of these features is completely dependant on
the filesystem the storage is using, which may not support the extra data, attribute or flags required.
"""
import logging
import os
import stat
import sys
from pathlib import Path
from typing import Union

logger = logging.getLogger(__name__)


if sys.platform.startswith("win"):

    def set_remote_file_security(path: Union[str, Path]):
        """
        Windows uses a custom system for storing this information that is only available on NTFS filesystems, called
        Alternate Data Streams. It works like if the file would have sub-files.
        """
        try:
            s = os.lstat(path)
            if stat.S_ISREG(s.st_mode):
                with open(f"{path}:Zone.Identifier", "wb") as f:
                    # NOTE: ZoneId=3 is the "URLZONE_INTERNET" value, for most of the content on the internet.
                    f.write(b"[ZoneTransfer]\r\nZoneId=3\r\n")
        except Exception as e:
            if not isinstance(e, OSError):
                logger.exception("Unexpected error for writing zone security ADS")


elif sys.platform.startswith("linux"):

    def set_remote_file_security(path: Union[str, Path]):
        """
        On Linux there is no specific feature for this, generally the executable permission flag provides a suitable
        protection against executing a file without checking its safety.
        """
        try:
            s = os.lstat(path)
            if stat.S_ISREG(s.st_mode) and s.st_mode & 0o111:
                os.chmod(path, s.st_mode & 0o666)
        except Exception as e:
            if not isinstance(e, OSError):
                logger.exception("Unexpected error for unsetting executable permission")


elif sys.platform.startswith("darwin"):

    def set_remote_file_security(path: Union[str, Path]):
        """
        On MacOSX the extra attributes features on a file is utilized to record remote file sources.
        The general UNIX executable permission flag provides a suitable protection against executing a file without
        checking its safety.
        """
        # TODO: Implement xattr com.apple.metadata:kMDItemWhereFroms with plistlib maybe?
        try:
            s = os.lstat(path)
            if stat.S_ISREG(s.st_mode) and s.st_mode & 0o111:
                os.chmod(path, s.st_mode & 0o666)
        except Exception as e:
            if not isinstance(e, OSError):
                logger.exception("Unexpected error for unsetting executable permission")


else:
    raise NotImplementedError()
