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

#
# Usage:
# AGI(/etc/asterisk/agi/mqtt,/etc/asterisk/agi/mqtt.cfg,calls/missed)
# or, to override the extension:
# AGI(/etc/asterisk/agi/mqtt,/etc/asterisk/agi/mqtt.cfg,calls/missed,+43123456789)
#

import sys
reload(sys)
sys.setdefaultencoding('utf-8')

from ConfigParser import ConfigParser
import paho.mqtt.client as paho
from pymessaging.sms import SmsDeliver

import json

from os import getpid,uname
from pprint import pprint

import sqlite3
from sqlite3 import Error

from os import remove,system

client_name='agi-'+uname()[1]+'-'+str(getpid())

conffile, topic, base64 = sys.argv[1:4]

config = ConfigParser()
config.add_section('mqtt')
config.add_section('sms')
# set defaults for anonymous auth
config.set('mqtt', 'username', '')
config.set('mqtt', 'password', '')
config.set('mqtt', 'port', '1883')
config.set('sms', 'tmpfile', '/tmp/sms.db')
config.read(conffile)

mqtt_server = config.get('mqtt', 'server')
mqtt_port = config.getint('mqtt', 'port')
mqtt_username = config.get('mqtt', 'username')
mqtt_password = config.get('mqtt', 'password')
sms_db = config.get('sms','tmpfile')

try:
  conn = sqlite3.connect(sms_db)
except:
  remove(sms_db)
  conn = sqlite3.connect(sms_db)

agi = []
while 1:
    line = sys.stdin.readline()
    if not line or line == "\n":
        break
    agi.append(line)

agi = dict([line.rstrip('\n').replace('agi_', '', 1).split(': ', 1) for line in agi])

agi['base64'] = base64

full_text=""
try:
  sms=SmsDeliver(base64.decode('base64').split('\r\n')[1])
  if 'cnt' in sms.data:
    sms_type='sms-multipart'
    part_count=sms.data['cnt']
    part_number=sms.data['seq']
    ref=sms.data['ref']
    agi['part-count']=part_count
    agi['part-number']=part_number
    agi['ref']=ref
  else:
    sms_type='sms'
  agi['sms-type']=sms_type
  sms_text=sms.data['text'].encode('utf-8')
  agi['sms_text']=sms_text
  if sms_type=='sms':
    full_text=sms_text
  else:
    cur = conn.cursor()
    cur.execute("create table if not exists sms_parts (ref integer,cnt integer,seq integer,datetime timestamp default current_timestamp,text varchar(255))")  
    cur.execute("insert into sms_parts(ref,cnt,seq,text) values(%s,%s,%s,\'%s\')" % (ref,part_count,part_number,sms_text))
    cur.execute("select count(*),cnt from sms_parts where ref=%s" % (ref))
    received,cnt=cur.fetchone()
    if received==cnt:
      cur.execute("select text from sms_parts where ref=%s order by seq" % (ref))
      full_text=''.join(rec[0] for rec in cur.fetchall())
#      full_text=full_text.replace("\"","")
      agi["full_text"]=full_text
      cur.execute("delete from sms_parts where ref=%s" % (ref))
    conn.commit()  
except:
  raise

if full_text:
  print full_text
  f1=open("/tmp/sms.log","w+")
  f1.write(full_text.strip().encode('utf-8'))
  f1.close()
  
def agi_exit(rc, *args):
    if rc != 0:
        print "VERBOSE rc=%s %s" % (rc, args)
    sys.exit(rc)

def on_connect(mosq, rc, *args):
    if rc != 0:
        agi_exit(1, "Connection failed: %d" % rc)

def on_publish(mosq, *args):
    # done
    agi_exit(0)

client = paho.Client(client_name)
client.username_pw_set(mqtt_username, mqtt_password)
client.connect(mqtt_server, port=mqtt_port)
client.on_connect = on_connect
client.on_publish = on_publish

client.publish(topic, payload=json.dumps(agi))
client.loop()
agi_exit(1, "Message publish timed out")