# -*- coding: utf-8 -*-
"""Platforms.

Utilities dealing with platform specifics: signals, daemonization,
users, groups, and so on.
"""
from __future__ import absolute_import, print_function, unicode_literals

import atexit
import errno
import math
import numbers
import os
import platform as _platform
import signal as _signal
import sys
import warnings
from collections import namedtuple
from contextlib import contextmanager

from billiard.compat import close_open_fds, get_fdmax
# fileno used to be in this module
from kombu.utils.compat import maybe_fileno
from kombu.utils.encoding import safe_str

from .exceptions import SecurityError
from .five import items, reraise, string_t
from .local import try_import

try:
    from billiard.process import current_process
except ImportError:  # pragma: no cover
    current_process = None

_setproctitle = try_import('setproctitle')
resource = try_import('resource')
pwd = try_import('pwd')
grp = try_import('grp')
mputil = try_import('multiprocessing.util')

__all__ = (
    'EX_OK', 'EX_FAILURE', 'EX_UNAVAILABLE', 'EX_USAGE', 'SYSTEM',
    'IS_macOS', 'IS_WINDOWS', 'SIGMAP', 'pyimplementation', 'LockFailed',
    'get_fdmax', 'Pidfile', 'create_pidlock', 'close_open_fds',
    'DaemonContext', 'detached', 'parse_uid', 'parse_gid', 'setgroups',
    'initgroups', 'setgid', 'setuid', 'maybe_drop_privileges', 'signals',
    'signal_name', 'set_process_title', 'set_mp_process_title',
    'get_errno_name', 'ignore_errno', 'fd_by_path', 'isatty',
)

# exitcodes
EX_OK = getattr(os, 'EX_OK', 0)
EX_FAILURE = 1
EX_UNAVAILABLE = getattr(os, 'EX_UNAVAILABLE', 69)
EX_USAGE = getattr(os, 'EX_USAGE', 64)
EX_CANTCREAT = getattr(os, 'EX_CANTCREAT', 73)

SYSTEM = _platform.system()
IS_macOS = SYSTEM == 'Darwin'
IS_WINDOWS = SYSTEM == 'Windows'

DAEMON_WORKDIR = '/'

PIDFILE_FLAGS = os.O_CREAT | os.O_EXCL | os.O_WRONLY
PIDFILE_MODE = ((os.R_OK | os.W_OK) << 6) | ((os.R_OK) << 3) | ((os.R_OK))

PIDLOCKED = """ERROR: Pidfile ({0}) already exists.
Seems we're already running? (pid: {1})"""

_range = namedtuple('_range', ('start', 'stop'))

C_FORCE_ROOT = os.environ.get('C_FORCE_ROOT', False)

ROOT_DISALLOWED = """\