"""Rads module

.. data:: rads.IMH_ROLE:

    The server's imh_role in salt
    *(str | None)*

.. data:: rads.IMH_CLASS:

    The server's imh_class in salt
    *(str | None)*

.. data:: rads.HAS_CPANEL:

    Whether /usr/local/cpanel/cpsrvd exists as a file
    *(bool)*

.. data:: rads.SECURE_USER:

    The secure user's username
    *(str)*

.. data:: rads.SECURE_FQDN:

    The secure user's fqdn
    *(str)*

.. data:: rads.STAFF_GROUPS:

    IMH employee group names
    *(list)*

.. data:: rads.SYS_USERS:

    System usernames. This also includes ``OUR_RESELLERS`` and ``SECURE_USER``
    *(list)*

.. data:: rads.SYS_MYSQL_USERS:

    System MySQL usernames
    *(list)*

.. data:: rads.OUR_RESELLERS:

    Our "main" resellers' usernames on shared, including root and tier2s
    *(list)*

.. data:: rads.SECURE_CRT_FILE:

    Path to secure user's ssl cert file. This is looked up when accessed for
    the first time, then cached for the remainder of execution.
    *(str | None)*

.. data:: rads.SECURE_CRT_ID:

    ID of the secure user's certificate ID used for cPanel API calls. This is
    looked up when accessed for the first time, then cached for the remainder of
    execution.
    *(str | None)*

.. data:: rads.SECURE_KEY_FILE:

    The secure user's ssl key file. This is looked up when accessed for
    the first time, then cached for the remainder of execution.
    *(str | None)*

.. data:: rads.CPANEL_EXTRA_SHARED_IPS:

    Any extra shared ips defined in /etc/reservedipreasons
    *(list)*

.. data:: rads.CPANEL_INMOTION_IPS:

    Any shared ips defined in /var/cpanel/mainips/inmotion
    *(list)*
"""

from typing import Union
from pathlib import Path
import platform
import re
from . import _globals

# pylint: disable=wrong-import-position,global-statement
IMH_ROLE, IMH_CLASS = _globals.read_server_role()
IMH_PROFILE = f"{IMH_ROLE}.{IMH_CLASS}" if IMH_ROLE else None
HAS_CPANEL = Path('/usr/local/cpanel/cpsrvd').is_file()
STAFF_GROUPS, SYS_USERS, SYS_MYSQL_USERS, OUR_RESELLERS = _globals.rads_json()
if IMH_ROLE == 'shared':
    SECURE_FQDN = re.sub('^[a-z-]+', 'secure', platform.node())
    SECURE_USER = _globals.get_secure_user(SECURE_FQDN)
    if SECURE_USER:
        SYS_USERS.append(SECURE_USER)
    CPANEL_EXTRA_SHARED_IPS = _globals.get_cpanel_inmotion_ips()
    CPANEL_INMOTION_IPS = _globals.get_cpanel_extra_shared_ips()
else:
    SECURE_FQDN, SECURE_USER = None, None
    CPANEL_EXTRA_SHARED_IPS, CPANEL_INMOTION_IPS = [], []

from . import color
from . import vz

if _globals.HAS_PARAMIKO:
    from . import ssh

# General functions (these also need __module__ set to appear in docs)
from ._email import send_email

from ._input import get_keypress, prompt_y_n

from ._locking import LockError, lock, wait_lock

from ._logging import setup_logging, setup_verbosity
from ._logging import LevelFilter, MultilineFormatter

from ._sa import get_cp_usage, SaUsage

from ._fsquota import QuotaCtl, QuotaError, QuotaNoUser, QuotasDisabled

from ._users import CpuserError, UserData, UserDomain
from ._users import get_login, get_homedir, get_primary_domain
from ._users import is_cpuser, all_cpusers, main_cpusers
from ._users import get_owner, is_child, get_children
from ._users import cpuser_safe, cpuser_suspended, whoowns
from ._users import DumbYamlLoader, get_plan

from ._tickets import make_ticket, TicketError

# Backwards compat imports
# pylint: disable=wrong-import-order
from cpapis import uapi, cpapi1, cpapi2, cpapi3, whmapi0, whmapi1, CpAPIError

# pylint: disable=cyclic-import
from . import semaphore

# Lazy lookup private value stores
_SECURE_KEY_FILE = None
_SECURE_CRT_ID = None
_SECURE_CRT_MODULUS = None


def __getattr__(name: str):
    """getattr hook to provide lazy attribute loading for slow values"""
    global _SECURE_KEY_FILE
    global _SECURE_CRT_MODULUS
    global _SECURE_CRT_ID
    if name == "SECURE_KEY_FILE":
        if not SECURE_USER:
            return None
        if _SECURE_KEY_FILE:
            return _SECURE_KEY_FILE
        global _SECURE_CRT_MODULUS
        if not _SECURE_CRT_MODULUS:
            # lookup SECURE_CRT_ID to populate _SECURE_CRT_MODULUS
            __getattr__('SECURE_CRT_ID')
        _SECURE_KEY_FILE = _globals.get_secure_key_file(
            SECURE_USER, _SECURE_CRT_MODULUS
        )
        return _SECURE_KEY_FILE
    if name == "SECURE_CRT_FILE":
        if not SECURE_USER:
            return None
        secure_crt_id = __getattr__('SECURE_CRT_ID')
        return f"/home/{SECURE_USER}/ssl/certs/{secure_crt_id}.crt"
    if name == "SECURE_CRT_ID":
        if not SECURE_USER or not SECURE_FQDN:
            return None
        if not _SECURE_CRT_ID:
            _SECURE_CRT_ID, _SECURE_CRT_MODULUS = _globals.get_secure_crt_info(
                SECURE_USER,
                SECURE_FQDN,
            )
        return _SECURE_CRT_ID
    raise AttributeError(f"No such attribute: {name}")


SECURE_KEY_FILE: Union[str, None]
SECURE_CRT_FILE: Union[str, None]
SECURE_CRT_ID: Union[str, None]
