#!/usr/bin/python3
# -*- mode: python; coding: utf-8 -*-
#
##########################################################################
# 00-network - manage networkd override structure
# Copyright © 2018 Pôle de compétences EOLE <eole@ac-dijon.fr>
#
# License CeCILL:
#  * in french: http://www.cecill.info/licences/Licence_CeCILL_V2-fr.html
#  * in english http://www.cecill.info/licences/Licence_CeCILL_V2-en.html
##########################################################################

"""Populate a per .network override

"""

from __future__ import absolute_import, print_function, unicode_literals

import sys
import os

import shutil

from pyeole.i18n import i18n
from pyeole.log import init_logging

from creole.client import CreoleClient
from creole import template
from creole.containers import is_lxc_enabled

_ = i18n('00-network')

NETPLAN_CONFIG_DIR = '/etc/netplan'
NETWORKD_CONFIG_DIR = '/etc/systemd/network'
EOLE_CONFIG_DIR = '/etc/eole/network'

log = None

def clean_netplan_configs(config):
    """Remove all files under `/etc/netplan/`

    """
    if config['eth0_method'] != 'non géré':
        log.debug(_('Cleanup netplan configuration'))
        for filename in os.listdir(NETPLAN_CONFIG_DIR):
            log.debug(_("Remove netplan file '{0}'").format(filename))
            os.remove(os.path.join(NETPLAN_CONFIG_DIR, filename))


def clean_networkd_configs():
    """Remove all files under `/etc/systemd/network/`

    """
    log.debug(_('Cleanup networkd override configuration'))
    for filename in os.listdir(NETWORKD_CONFIG_DIR):
        full_path = os.path.join(NETWORKD_CONFIG_DIR,
                                 filename)
        if not filename.startswith('10-netplan') or not os.path.isdir(full_path):
            continue

        log.debug(_("Remove networkd override directory '{0}'").format(full_path))
        shutil.rmtree(full_path)

def create_override_links(config):
    """Create the overrides links

    """
    log.debug(_('Create networkd override links'))

    if not os.path.isdir(EOLE_CONFIG_DIR):
            os.makedirs(EOLE_CONFIG_DIR, mode=0o755)

    for index in range(int(config['nombre_interfaces'])):
        name = config['nom_zone_eth{0}'.format(index)]
        try:
            engine = template.CreoleTemplateEngine()
            engine.instance_template('interface_{0}.conf'.format(index))
        except:
            log.info(_("File interface_{0}.conf not updated".format(index)))
        config_path = os.path.join(EOLE_CONFIG_DIR,
                                   'interface_{0}.conf'.format(index))
        override_dir = os.path.join(NETWORKD_CONFIG_DIR,
                                    '10-netplan-{0}.network.d'.format(name))
        link_path = os.path.join(override_dir, 'eole.conf')

        if not os.path.isdir(override_dir):
            log.debug(_("Create networkd override directory '{0}'").format(override_dir))
            os.makedirs(override_dir, mode=0o755)

        if not os.path.islink(link_path):
            log.info(_("Create link '{link}' -> '{config}'").format(link=link_path,
                                                                    config=config_path))
            os.symlink(config_path, link_path)

def main():
    global log
    log = init_logging(name=sys.argv[0], as_root=True, level='info')

    client = CreoleClient()
    config = client.get_creole()
    clean_netplan_configs(config)
    clean_networkd_configs()
    create_override_links(config)


if __name__ == "__main__":
    try:
        main()
    except Exception as error:
        log.error(_('Unable to setup per interface override: {error}').format(error=error))
