from bundlewrap.metadata import atomic

defaults = {
    'apt': {
        'packages': {
            'unbound': {},
            'unbound-anchor': {},
        },
    },
    'nameservers': {
        '127.0.0.1',
    },
    'systemd-timers': {
        'timers': {
            'unbound-refresh-root-hints': {
                'command': 'wget -q -O/etc/unbound/root-hints.txt https://www.internic.net/domain/named.root',
                'when': '{}:{}:00'.format(
                    node.magic_number % 24,
                    node.magic_number % 60,
                ),
            },
            'unbound-auto-restart': {
                'command': '/usr/local/sbin/unbound-auto-restart',
                'when': 'minutely',
            },
        },
    },
    'unbound': {
        'max_ttl': 3600,
        'cache_size': '512M',
    },
}

if node.has_bundle('telegraf'):
    defaults['telegraf'] = {
        'input_plugins': {
            'builtin': {
                'unbound': [{
                    'thread_as_tag': True,
                    'use_sudo': True
                }],
            },
        },
        'sudo_commands': {
            '/usr/sbin/unbound-control',
        },
    }



@metadata_reactor.provides(
    'unbound/threads',
    'unbound/cache_slabs',
)
def cpu_cores_to_config_values(metadata):
    num_cpus = metadata.get('vm/cpu', 1)

    return {
        'unbound': {
            'threads': num_cpus*2,
            'cache_slabs': 2**(num_cpus-1).bit_length(),
        },
    }


@metadata_reactor.provides(
    'firewall/port_rules',
)
def firewall(metadata):
    return {
        'firewall': {
            'port_rules': {
                '53/tcp': atomic(metadata.get('unbound/restrict-to', set())),
                '53/udp': atomic(metadata.get('unbound/restrict-to', set())),
            },
        },
    }
