"""Compat module to handle files security on Windows and Linux"""
from __future__ import absolute_import

import errno
import os  # pylint: disable=os-module-forbidden
import stat
import sys
from typing import Any
from typing import Dict
from typing import List
from typing import Optional

try:
    import ntsecuritycon
    import pywintypes
    import win32api
    import win32con
    import win32file
    import win32security
    import winerror
except ImportError:
    POSIX_MODE = True
else:
    POSIX_MODE = False


# Windows umask implementation, since Windows does not have a concept of umask by default.
# We choose 022 as initial value since it is the default one on most Linux distributions, and
# it is a decent choice to not have write permissions for group owner and everybody by default.
# We use a class here to avoid needing to define a global variable, and the potential mistakes
# that could happen with this kind of pattern.
class _WindowsUmask:
    """Store the current umask to apply on Windows"""
    def __init__(self) -> None:
        self.mask = 0o022


_WINDOWS_UMASK = _WindowsUmask()


def chmod(file_path: str, mode: int) -> None:
    """
    Apply a POSIX mode on given file_path:

      - for Linux, the POSIX mode will be directly applied using chmod,
      - for Windows, the POSIX mode will be translated into a Windows DACL that make sense for
        Certbot context, and applied to the file using kernel calls.