from inspect import cleandoc
from uuid import UUID

from bundlewrap.utils.text import italic

files = {
    '/etc/default/locale': {
        'content_type': 'mako',
        'needs': {
            'action:locale-gen',
        },
    },
    '/etc/hosts': {
        'content_type': 'mako',
    },
    '/etc/htoprc.global': {
        'source': 'htoprc',
    },
    '/etc/motd': {
        'content': '',
    },
    '/etc/environment': {
        'content_type': 'mako',
        'before': {
            'action:',
            'pkg_apt:',
            'pkg_pacman:',
        },
    },
}

locale_needs = set()
for locale in sorted(node.metadata.get('locale/installed')):
    actions[f'ensure_locale_{locale}_is_enabled'] = {
        'command': f"sed -i '/{locale}/s/^# *//g' /etc/locale.gen",
        'unless': f"grep -e '^{locale}' /etc/locale.gen",
        'triggers': {
            'action:locale-gen',
        },
        'needs': locale_needs,
    }
    locale_needs = {f'action:ensure_locale_{locale}_is_enabled'}

actions = {
    'locale-gen': {
        'triggered': True,
        'command': 'locale-gen',
    },
}

description = []

if not node.metadata.get('icinga_options/exclude_from_monitoring', False):
    description.append('icingaweb2: https://icinga.franzi.business/monitoring/host/show?host={}'.format(node.name))

if node.has_bundle('telegraf'):
    description.append('Grafana: https://grafana.kunsmann.eu/d/{}'.format(UUID(int=node.magic_number).hex[:10]))

if (
    not node.metadata.get('icinga_options/exclude_from_monitoring', False) or
    node.has_bundle('telegraf')
):
    description.append('') # divider line

if node.metadata.get('nginx/vhosts', {}):
    description.append('nginx vhosts:')

    for vname, vconfig in sorted(node.metadata.get('nginx/vhosts', {}).items()):
        if vconfig.get('ssl', 'letsencrypt') is not None:
            proto = 'https'
        else:
            proto = 'http'

        domain = vconfig.get('domain', vname)

        description.append('  {}: {}://{}{}'.format(
            vname,
            proto,
            domain,
            vconfig.get('website_check_path', '/'),
        ))

    if node.metadata.get('description', []):
        description.append('') # divider line

for line in node.metadata.get('description', []):
    description.append('# {}'.format(italic(line)))

if description:
    files['/etc/node.description'] = {
        'content': '\n'.join(description) + '\n',
    }
else:
    files['/etc/node.description'] = {
        'delete': True,
    }
