# -*- coding: UTF-8 -*-
###########################################################################
# Eole NG - 2007
# Copyright Pole de Competence Eole  (Ministere Education - Academie Dijon)
# Licence CeCill  cf /root/LicenceEole.txt
# eole@ac-dijon.fr
###########################################################################
"""
Fichier de configuration de l'application Zephir
"""
from os.path import join, dirname, abspath, isdir, isfile
from os import listdir
from creole.client import CreoleClient
import locale
from twisted.python import log
log.FileLogObserver.timeFormat = "%Y/%m/%d %H:%M:%S %Z"

# XXX FIXME / config template
conf = CreoleClient()

##########################################################################
# NE MODIFIER QUE CE TABLEAU
##########################################################################
TABLE_SUPPORT = [
    {"distibution": "xenial",
     "id": 20,
     "release": "2.6.0",
     "maintenue": True,
     "creole": "creole4",
     "envole": "5",
     "upgrade_max_release_id": None,
     "available_modules": ['eolebase', 'esbl', 'eclair', 'hapy', 'horus', 'scribe', 'seth', 'sphynx', 'zephir'],
     },
    {"distibution": "xenial",
     "id": 21,
     "release": "2.6.1",
     "maintenue": True,
     "creole": "creole5",
     "envole": "6",
     "upgrade_max_release_id": None,
     "available_modules": ['eolebase', 'ecdl', 'esbl', 'amon', 'eclair', 'hapy', 'horus', 'scribe', 'seshat', 'seth', 'sphynx', 'thot', 'amonecole', 'zephir'],
     },
    {"distibution": "xenial",
     "id": 22,
     "release": "2.6.2",
     "maintenue": True,
     "creole": "creole5",
     "envole": "6",
     "upgrade_max_release_id": None,
     "available_modules": ['eolebase', 'ecdl', 'esbl', 'amon', 'eclair', 'hapy', 'horus', 'scribe', 'seshat', 'seth', 'sphynx', 'thot', 'amonecole', 'amonecoleeclair', 'zephir'],
     },
    {"distibution": "bionic",
     "id": 30,
     "release": "2.7.0",
     "maintenue": True,
     "creole": "creole5",
     "envole": "6",
     "upgrade_max_release_id": None,
     "available_modules": ['eolebase', 'esbl', 'amon', 'hapy', 'seshat', 'seth', 'sphynx', 'thot', 'zephir'],
     },
    {"distibution": "bionic",
     "id": 31,
     "release": "2.7.1",
     "maintenue": True,
     "creole": "creole5",
     "envole": "7",
     "upgrade_max_release_id": None,
     "available_modules": ['eolebase', 'amon', 'eclair', 'hapy', 'horus', 'scribe', 'seshat', 'seth', 'sphynx', 'thot', 'zephir'],
     },
    {"distibution": "bionic",
     "id": 32,
     "release": "2.7.2",
     "maintenue": True,
     "creole": "creole5",
     "envole": "7",
     "upgrade_max_release_id": None,
     "available_modules": ['eolebase', 'amon', 'eclair', 'hapy', 'horus', 'scribe', 'seshat', 'seth', 'sphynx', 'thot', 'zephir'],
     },
    {"distibution": "focal",
     "id": 40,
     "release": "2.8.0",
     "maintenue": True,
     "creole": "creole5",
     "envole": "8",
     "upgrade_max_release_id": None,
     "available_modules": ['eolebase', 'hapy', 'scribe', 'seshat', 'seth', 'sphynx', 'zephir'],
     },
    {"distibution": "focal",
     "id": 41,
     "release": "2.8.1",
     "maintenue": True,
     "creole": "creole5",
     "envole": "8",
     "upgrade_max_release_id": None,
     "available_modules": ['eolebase', 'hapy', 'scribe', 'seshat', 'seth', 'sphynx', 'zephir', 'amon', 'amonecole'],
     },
    {"distibution": "jammy",
     "id": 42,
     "release": "2.9.0",
     "maintenue": True,
     "creole": "creole5",
     "envole": "9",
     "upgrade_max_release_id": None,
     "available_modules": ['eolebase', 'hapy', 'scribe', 'seshat', 'seth', 'sphynx', 'zephir', 'amon', 'amonecole'],
     },
    {"distibution": "noble",
     "id": 43,
     "release": "2.10.0",
     "maintenue": True,
     "creole": "creole5",
     "envole": "9",
     "upgrade_max_release_id": None,
     "available_modules": ['eolebase', 'hapy', 'scribe', 'seshat', 'seth', 'sphynx', 'zephir', 'amon', 'amonecole'],
     },
    ]
##########################################################################
# NE MODIFIER EN DESSOUS DE CETTE LIGNE
##########################################################################

charset = "UTF-8"

ADRESSE_LDAP = conf.get_creole("adresse_ip_ldap")
ADRESSE_ZEPHIR = conf.get_creole("nom_domaine_machine")
BASE_LDAP = conf.get_creole("ldap_base_dn")
LDAP_CLIENT = conf.get_creole('activer_client_ldap')
if LDAP_CLIENT == "local":
    LDAP_TLS = "non"
else:
    LDAP_TLS = conf.get_creole("ldap_tls", "non") or "non"
PORT_HTTP = "8090"
PORT_ZEPHIR = "7080"
PORT_WEB = 8070
NO_LOCAL_AGENTS = conf.get_creole("no_local_agents", "non") or "non"

NOBODY_GID = NOBODY_UID = 65534

LOG_ACTIONS = False
if (conf.get_creole('log_actions', 'non') or 'non') == 'oui':
    # Logguer les appels xmlrpc authentifiés dans les logs du backend
    LOG_ACTIONS = True

USE_THREADS = False
# mise en cache des configurations creole
if (conf.get_creole('zephir_use_threads', 'oui') or 'oui') == 'oui':
    # conservation en mémoire de la configuration creole des serveurs
    USE_THREADS = True
CREOLE_CACHE = False
# mise en cache des configurations creole
if (conf.get_creole('zephir_creole_cache', 'oui') or 'oui') == 'oui':
    # conservation en mémoire de la configuration creole des serveurs
    CREOLE_CACHE = True

# répertoire de base appli
ROOT_DIR = "/usr/share/zephir/"
PORT_AGENT = "8090"
AGENT_DIR = "agents"
CLIENT_UPDATE_HOST = "eoleng.ac-dijon.fr"
CLIENT_NG_URL = "/eoleng/eole-%s-security/%s"
SERVEURS_MAJ_CLIENTS = conf.get_creole('serveur_maj_clients', []) or []

MAIL_ADRESSE = "localhost"
MAIL_PORT = 25
MAIL_ACCOUNT = conf.get_creole("system_mail_from", "") or ""

# répertoire de base des donnees backend
PATH_ZEPHIR = "/var/lib/zephir/"
PATH_TEMP = join("/tmp", "zephir_temp")
PATH_MODULES = PATH_ZEPHIR + 'modules/'
ADRESSE_SAUVEGARDE = join(PATH_ZEPHIR, 'user_prefs')

# possibilité de charger par variante
LOAD_BY_VARIANTE = conf.get_creole('zephir_load_by_variante') == 'oui'

# certificats par défaut
#cert_file = conf.get_creole('server_cert', '/etc/eole/ssl/eole.crt') or '/etc/eole/ssl/eole.crt'
#key_file = conf.get_creole('server_key', '/etc/eole/ssl/eole.key') or '/etc/eole/ssl/eole.key'
SSL_dir = '/etc/zephir/ssl'
certname = 'zephir'
cert_file = SSL_dir + '/certs/{0}.pem'.format(certname)
key_file = SSL_dir + '/private/{0}.key'.format(certname)

# manager prelude par défaut
PRELUDE_PORT = 4691

# détails des distributions gérées (nom_de_code, version_eole, maintenue)
DISTRIBS = {dist['id']: (dist['distibution'], dist['release'], dist['maintenue']) for dist in TABLE_SUPPORT}

dist_keys = list(DISTRIBS.keys())
dist_keys.sort()

def get_next_dist(current):
    """returns identifier for distribution following given current number"""
    if current in dist_keys and dist_keys.index(current) < len(dist_keys) -1:
        return dist_keys[dist_keys.index(current) + 1]
    # pas de distribution suivante
    return -1

# version de creole en fonction de la version de distribution eole
CREOLE_VERSIONS = {dist['id']: dist['creole'] for dist in TABLE_SUPPORT}


# versions d'envole en fonction de la version eole
ENVOLE_VERSION = {dist['id']: dist['envole'] for dist in TABLE_SUPPORT if dist['envole'] is not None}

liste_modules = {}
PATH_DEF_MODULES = join(ROOT_DIR, 'default_modules')
# liste des modules eole, classés par version (la version 1 n'est plus gérée)
for num_dist in list(DISTRIBS.keys()):
    # recherche des modules Eole NG par défaut
    modules = []
    dist_dir = join(PATH_DEF_MODULES, str(num_dist))
    # le répertoire peut ne pas être créé (ex: restauration avant instance)
    if isdir(dist_dir):
        for mod_name in listdir(dist_dir):
            # on ignore les fichiers ~, .bak, etc...
            if isfile(join(dist_dir, mod_name)) and not \
                    (mod_name.endswith('~') or \
                    mod_name.endswith('.bak') or \
                    mod_name.endswith('.swp')):
                    # on vérifie qu'un répertoire de dictionnaires est bien présent pour ce module
                    # if isdir(join(ROOT_DIR, 'dictionnaires', mod_name)):
                    modules.append(mod_name)
    liste_modules[num_dist] = modules

# migrations autorisées. la déclaration n'est pas nécessaire entre 2 versions se suivant directement (voir DISTRIBS)
default_upgrades = {}
current_version = '.'.join(TABLE_SUPPORT[-1]['release'].split('.')[0:2])
dist_infos = {dist['id']: {'version': '.'.join(dist['release'].split('.')[0:2]), 'upgrade_max_release_id': dist['upgrade_max_release_id']} for dist in TABLE_SUPPORT}
for idx, dist in enumerate(dist_keys):
    if dist_infos[dist]['version'] != current_version:
        dists = dist_keys[idx+2:]
        if dist_infos[dist]['upgrade_max_release_id'] is not None:
            default_upgrades[dist] = [dist_ for dist_ in dists if dist_ <= dist_infos[dist]['upgrade_max_release_id']]
        else:
            default_upgrades[dist] = dists

# liste des modules autorisés à migrer de plus d'une version
allowed_upgrades = {}
all_modules = set()
available_modules = {}
for dist in TABLE_SUPPORT:
    for module in dist['available_modules']:
        all_modules.add(module)
    available_modules[dist['id']] = dist['available_modules']
all_modules.remove('zephir')
for module in all_modules:
    allowed_upgrades[module] = {}
    for dist, subdists in default_upgrades.items():
        if module not in available_modules[dist]:
            continue
        avail_dists = []
        for subdist in subdists:
            if module in available_modules[subdist]:
                avail_dists.append(subdist)
        if avail_dists:
            allowed_upgrades[module][dist] = avail_dists

# définition des migrations entre modules (adaptation de configuration nécessaire)
allowed_migrations = {}
dist_infos = {dist['id']: {'version': '.'.join(dist['release'].split('.')[0:2]), 'upgrade_max_release_id': dist['upgrade_max_release_id']} for dist in TABLE_SUPPORT}
for idx, dist in enumerate(dist_keys):
    if dist_infos[dist]['version'] != current_version:
        allowed_migrations[dist] = []
        for subdist in dist_keys[idx+1:]:
            if dist_infos[subdist]['version'] != dist_infos[dist]['version']:
                allowed_migrations[dist].append(subdist)

# liste des modules autorisés à être modifiés (édition de serveur)
default_mod_edits = {'amon':['amonecole'], 'amonecole':['amon']}
allowed_mod_edits = {
                     20: default_mod_edits,
                     21: default_mod_edits,
                     22: default_mod_edits,
                     30: {},
                     31: {},
                     32: {},
                     40: {},
                     41: {},
                     42: {},
                     43: {},
                    }

# liste des verrous existants et de leurs dépendances
verrous = {'uucp':['Execution des tâches Zephir'],
           'sauvegarde':['Maj-Auto','Maj-Cd'],
           'maj':[],
           'configure':[],
           'reconfigure':[]}

# types  de fichiers à sauvegarder/envoyer
data_files = {0:('Tout', ['dicos','patchs','fichiers_perso','fichiers_zephir','zephir.eol','dico.eol','auth_keys','droits_zephir', 'droits_variante']),
              1:('Dictionnaires/templates/patchs/configuration/clés ssh', ['dicos','patchs','fichiers_perso','zephir.eol','auth_keys']),
              2:('Dictionnaires/templates/patchs', ['dicos','patchs','fichiers_perso']),
              3:('Fichiers divers/paquets', ['fichiers_zephir', 'droits_zephir', 'droits_variante']),
              4:('Configuration seulement (config.eol)', ['zephir.eol']),
              5:('Clés ssh seulement', ['auth_keys']),
             }

# libellés à affecter aux différents types de restrictions de ressources, table et champs correspondant (pour validation)
type_res_label =  {'rne':('numéro RNE', 'etablissements', 'rne'),
                   'groupe':('numéro de groupe', 'groupes_serveurs', 'id'),
                   'id_s':('numéro de serveur', 'serveurs', 'id'),
                   'id_var':('numéro de variante', 'variantes', 'id'),
                   'id_mod':('numéro de module', 'modules', 'id'),
                  }

# correspondance des caractères pour les xml des agents eole1
xml_table={'\\xc9':'\\xc3\\xa9',
           '\\xe9':'\\xc3\\xa9',
           '\\xc8':'\\xc3\\xa8',
           '\\xe8':'\\xc3\\xa8',
           '\\xf4':'\\xc3\\xb4',
           '\\xe0':'\\xc3\\xa0',
           }

# liste des variables creole donnant l'adresse d'un portail etablissement sur Scribe/Amonecole
var_portail = ['web_url', 'posh_url', 'scribe_envole_url', 'cas_domainname']
mod_portail = ['scribe', 'amonecole']

# temps entre chaque vérification des timeout (secondes)
SCAN_DELAY = 300
