#!/usr/bin/python
# -*- coding: utf-8 -*-

import sys
import paho.mqtt.publish as publish # pip install paho-mqtt
import configparser

sendto  = sys.argv[1]
subject = sys.argv[2]
message = sys.argv[3]

config = configparser.ConfigParser()
config.read('/etc/zabbix/zabbix-alert-mqtt.conf')

hostname = config.get('DEFAULT', 'hostname', fallback='localhost')
port     = config.getint('DEFAULT', 'port', fallback=1883)
username = config.get('DEFAULT', 'username', fallback=None)
password = config.get('DEFAULT', 'password', fallback=None)
topic    = config.get('DEFAULT', 'topic', fallback='zabbix')
qos      = config.getint('DEFAULT', 'qos', fallback=0)

if config.has_section(sendto):
    if config.has_option(sendto, 'hostname'):
        hostname = config.get(sendto, 'hostname')
    if config.has_option(sendto, 'port'):
        port = config.getint(sendto, 'port')
    if config.has_option(sendto, 'username'):
        username = config.get(sendto, 'username')
    if config.has_option(sendto, 'password'):
        password = config.get(sendto, 'password')
    if config.has_option(sendto, 'topic'):
        topic = config.get(sendto, 'topic')
    if config.has_option(sendto, 'qos'):
        qos = config.getint(sendto, 'qos')

auth = None

if username is not None:
    auth = {
        'username' : username,
        'password' : password
    }

tls = None # TODO

if subject:
    topic = topic + "/" + subject.lower()

publish.single(topic, message, hostname=hostname, port=port, qos=qos, auth=auth, tls=tls)
