#!/usr/bin/python

# Application for reading a GMail account and sening and SMS
# to the number in the subject.
# Author: Saul Ibarra Corretge aka saghul <saghul@gmail.com>
# License: GPLv3

import imaplib
import commands
import sys
import re

user = ""
password = ""

mobile_regex = "6\d{8}"
modem_device = "huawei1"

gmail = imaplib.IMAP4_SSL('imap.gmail.com', 993)
status, data = gmail.login(user, password)

if status == 'OK':
    status, count = gmail.select('Inbox')
    if status == 'OK':
        status, messages = gmail.search(None, '(UNSEEN)')
        if status == 'OK':
            for msg in messages[0].split(' '):
                status, data = gmail.fetch(msg, '(BODY[TEXT] BODY[HEADER.FIELDS (SUBJECT)] BODY[HEADER.FIELDS (FROM)])')
                if status == 'OK':
                    body = data[0][1]
                    subject = data[1][1]
                    # from_ = data[2][1]
                    m = re.search(mobile_regex, subject)
                    if m:
                        num = m.group().strip()
                        # SMS can only be 160 chars long
                        text = body[:160].strip()

                        # We can now send the SMS
                        cmd = "asterisk -rx 'originate console/dsp application sebisendsms %s|%s|\"%s\"'" % (modem_device, num, text)
                        (exitstatus, outtext) = commands.getstatusoutput(cmd)
                        print "Message sent: ",outtext
                        # Mark message as read so we don't parse it again
                        gmail.store(msg, '+FLAGS', '\\Seen')
                else:
                    print "ERROR: couldn't fetch messages.\n"
                    sys.exit(1)
            # We are done.
            sys.exit(0)
        else:
            print "ERROR: could not find unread messages.\n"
            sys.exit(1)
else:
    print "ERROR: incorrect login.\n"
    sys.exit(1)


