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

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

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

import sqlite3
from sqlite3 import Error

from tempfile import mkstemp
from shutil import move

conffile = sys.argv[1:2]

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

sms_db = config.get('sms','tmpfile')

try:
  conn = sqlite3.connect(sms_db)

  cur = conn.cursor()
  cur.execute("select ref from sms_parts group by ref having max(datetime) is null or (julianday('now')-julianday(max(datetime)))>0.005;")
  refs=cur.fetchall()
  for ref in refs:
    cur.execute("select text from sms_parts where ref=%s order by seq" % (ref))
    full_text=''.join(rec[0] for rec in cur.fetchall()).replace("\"","")
    f,path=mkstemp(suffix=".call")
    f=open(path,"w")
    f.write("Application: Dial\n")
    f.write("Channel: Local/smsraw@DID_mobile\n")
    f.write("Context: smsraw\n")
    f.write("Setvar: SMS_FULL_TEXT=%s" % full_text)
    f.close()
    move(path,'/var/spool/asterisk/outgoing')
    cur.execute("delete from sms_parts where ref=%s" % (ref))
    conn.commit()

except:
  None