defaults = {
    'apt': {
        'unattended-upgrades': {
            'day': 5,
            'hour': 21,
        },
    },
    'icinga2_api': {
        'apt': {
            'services': {
                'UNATTENDED UPGRADES': {
                    'command_on_monitored_host': '/usr/local/share/icinga/plugins/check_unattended_upgrades',
                },
            },
        },
        'nginx': {
            'services': {
                'NGINX PROCESS': {
                    'command_on_monitored_host': '/usr/local/share/icinga/plugins/check_systemd_unit nginx',
                },
            },
        },
    },
}


@metadata_reactor.provides(
    'cron/jobs/upgrade-and-reboot'
)
def patchday(metadata):
    day = metadata.get('apt/unattended-upgrades/day')
    hour = metadata.get('apt/unattended-upgrades/hour')

    return {
        'cron': {
            'jobs': {
                'upgrade-and-reboot': '{minute} {hour} * * {day}    root    /usr/local/sbin/upgrade-and-reboot'.format(
                    minute=node.magic_number % 30,
                    hour=hour,
                    day=day,
                ),
            },
        },
    }


@metadata_reactor.provides(
    'icinga2_api/nginx/services',
)
def monitoring(metadata):
    services = {}

    for vname, vconfig in metadata.get('nginx/vhosts', {}).items():
        domain = vconfig.get('domain', vname)

        if 'website_check_path' in vconfig and 'website_check_string' in vconfig:
            services['NGINX VHOST {} CONTENT'.format(vname)] = {
                'check_command': 'check_http_wget',
                'vars.http_wget_contains': vconfig['website_check_string'],
                'vars.http_wget_url': 'https://{}{}'.format(domain, vconfig['website_check_path']),
                'vars.notification.sms': True,
            }

        if vconfig.get('check_ssl', True):
            services['NGINX VHOST {} CERTIFICATE'.format(vname)] = {
                'check_command': 'check_https_cert_at_url',
                'vars.domain': domain,
                'vars.notification.mail': True,
            }

    return {
        'icinga2_api': {
            'nginx': {
                'services': services,
            },
        },
    }
