from bundlewrap.metadata import atomic

defaults = {
    'apt': {
        'packages': {
            'mosquitto': {},
            'mosquitto-clients': {},
            'python3-paho-mqtt': {}, # for telegraf plugin
        },
    },
    'icinga2_api': {
        'mosquitto': {
            'services': {
                'MOSQUITTO PROCESS': {
                    'command_on_monitored_host': '/usr/lib/nagios/plugins/check_procs -C mosquitto -c 1:',
                },
            },
        },
    },
    'mosquitto': {
        'listeners': {
            '1883': {},
        },
    },
}


@metadata_reactor.provides(
    'firewall/port_rules',
)
def firewall(metadata):
    sources = metadata.get('mosquitto/restrict-to', {'*'})
    result = {}

    for listener in metadata.get('mosquitto/listeners').keys():
        result[f'{listener}/tcp'] = atomic(sources)

    return {
        'firewall': {
            'port_rules': result,
        },
    }


@metadata_reactor.provides(
    'telegraf/input_plugins/execd/tasmota',
)
def telegraf(metadata):
    topic = metadata.get('mosquitto/tasmota-telegraf-topic', None)

    if not topic:
        return {}

    return {
        'telegraf': {
            'input_plugins': {
                'execd': {
                    'tasmota': {
                        'command': [
                            '/usr/local/bin/tasmota-telegraf-plugin',
                            '127.0.0.1',
                            topic
                        ],
                        'signal': 'none',
                        'restart_delay': '1s',
                        'data_format': 'influx',
                    },
                },
            },
        },
    }
