#!/usr/bin/python3
"""
   Subscribes to the mqtt topic sent by Naemon/Nagios notification command.

   Parses the message and constructs an SMS message.

   Using the Twilio client API, sends a text message to the user.

   This script runs forever so it should be monitored by supervisord


   TODO:
       send the message id to mqtt
       
   DEPENDENCIES:
       The twilio library must be at 6.4.3+ or the create function will generate a json error, 
       must be str not bytes.

   DEPENDENCIES:
       For python 3, twilio 6.4.3 is required
"""

import paho.mqtt.client as mqtt
import configparser
import json
from twilio.rest import Client

DEBUG = True 

""" Call back from mqtt connect """
def on_connect(client,config,flags,rc):
    print("Connected with result code "+str(rc))
    # Subscribing in on_connect() means that if we lose the connection and
    # reconnect then subscriptions will be renewed.
    client.subscribe(Config.get('smssender','mqtt_subscribe_sms_send'))


        
""" Connects to twilio and sends the sms message """
def smsout(sms,fromuser,subject,message,config):

# Note to self: these will eventually be moved to the config file
    # Your Account SID from twilio.com/console
    account_sid = config.get('twilio','account_sid')
    auth_token = config.get('twilio','auth_token')
    sms_phone = config.get('twilio','phone_number')

    client = Client(account_sid, auth_token)

    message = client.messages.create(
        to=sms, 
        from_=sms_phone,
        body=message)

    print(message.sid)

def on_message(client, config, msg):
    if DEBUG:
        print(msg.topic+" "+msg.payload.decode('utf8'))
    dmsg = json.loads(msg.payload.decode('utf8'))
    if DEBUG:
        print(dmsg)
    smsout(dmsg["sms"],"smssender <smssender@pandavista.org>","broken",dmsg['message'],config)

Config = configparser.ConfigParser()
Config.read("/opt/sitepipe/etc/sitepipe/config.ini")

MQTT_BROKER = Config.get('client','mqtt_broker')
MQTT_PORT = Config.getint('client','mqtt_port')
MQTT_KEEPALIVE = Config.getint('client','mqtt_keepalive')
MQTT_SUBSCRIBE_MAIL_SEND = Config.get('smssender','mqtt_subscribe_sms_send')
client = mqtt.Client(userdata=Config)
client.on_connect = on_connect
client.on_message = on_message

client.connect(MQTT_BROKER,MQTT_PORT,MQTT_KEEPALIVE)

client.loop_forever()
