from os.path import join

check_commands = {}

for _, bundle_config in node.metadata.get('icinga2_api', {}).items():
    for service, service_config in bundle_config.get('services', {}).items():
        # The default for check_command is also set in metadata.py
        # and in icinga2 bundle
        if (
            service_config.get('check_command', 'sshmon') == 'sshmon' and
            'vars.sshmon_command' in service_config and
            'command_on_monitored_host' in service_config
        ):
            check_commands[service_config['vars.sshmon_command']] = service_config['command_on_monitored_host']


users = {
    'sshmon': {
        'password_hash': 'x',
        'home': '/home/sshmon',
    },
}

with open(join(repo.path, 'data', 'sshmon', 'sshmon.pub'), 'r') as fp:
    pubkey = fp.read().strip()

files = {
    '/etc/sshmon.cfg': {
        'content_type': 'mako',
        'context': {
            'check_commands': check_commands,
        },
    },
    '/etc/sudoers.d/sshmon': {
        'source': 'sudoers',
        'content_type': 'mako',
        'context': {
            'check_commands': check_commands,
        },
    },
    '/usr/local/sbin/sshmon': {
        'mode': '0755',
    },
    '/home/sshmon/.ssh/authorized_keys': {
        'content': 'command="/usr/local/sbin/sshmon" {}\n'.format(pubkey),
        'owner': 'sshmon',
        'mode': '0400',
    },
}

for check in {
    'cpu_stats',
    'forgejo_for_new_release',
    'github_for_new_release',
    'http_url_for_string',
    'http_wget',
    'https_certificate_at_url',
    'mounts',
    'oom_killer',
    'pypi_for_new_release',
    'ram',
    'systemd_unit',
}:
    files["/usr/local/share/icinga/plugins/check_{}".format(check)] = {
        'mode': "0755",
    }


if node.has_bundle('pacman'):
    symlinks['/usr/lib/nagios/plugins'] = {
        'target': '/usr/lib/monitoring-plugins',
        'needs': {
            'pkg_pacman:monitoring-plugins',
        },
    }
