#!/usr/bin/python
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.

# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.

# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
# Copyright (c) 2013 - SUSE <cbosdonnat@suse.com>
import imaplib, email, re, subprocess, os.path

def initGit():
    if !os.path.exists('.git/config'):
        subprocess.call(['git', 'init'])
    

def subject_to_filename(subject):
    filename = None
    # TODO Fix the project name to your need
    newRe = "^\[LibreOffice\] New proposal by ([^:]*): (.*)"
    updateRe = "^\[LibreOffice\] Update by (.*) to proposal: (.*)"
    result = re.match(updateRe, subject)
    if result:
        filename = "%s-%s" % (result.group(1),result.group(2))
    else:
        result = re.match(newRe, subject)
        if result:
            filename = "%s-%s" % (result.group(1),result.group(2))

    # Remove "/" from filenames
    # TODO There may be some more characters to remove
    if filename != None:
        filename = filename.translate(None, '/')
    return filename

def main():
    initGit()

    M = imaplib.IMAP4_SSL('your IMAP server getting the Melange notifications', 993)
    M.login('some account', 'some pass')
    M.select()

    # TODO My mail server doesn't provide support for sort command but provides them in proper
    # order. You may want to use the sort command depending on your IMAP server capabilities.
    typ, ids = M.search(None, 'UNSEEN', 'FROM', '"no-reply@google-melange.appspotmail.com"')
    print ids
    for mail_id in ids[0].split():
        typ, data = M.fetch(mail_id, '(RFC822)')
        msg = email.message_from_string(data[0][1])
        subject = msg['Subject'].translate(None, '\r\n')
        filename = subject_to_filename(subject)
        if filename != None:
            application = None
            for part in msg.walk():
                if part.get_content_type() == 'text/html':
                    application = part.get_payload(decode=1)
                    newApplication = !os.path.exists(filename)
                    # dump the mail content to a file
                    f = open(filename, 'w')
                    f.write(application)
                    f.close()
                    # git commit it
                    subprocess.call(['git', 'add', filename])
                    message = '"Application update"'
                    if newApplication:
                        message = '"New Application"'
                    subprocess.call(['git', 'commit', '-m', message])
        else:
            # Mark unmatching mails as unseen
            M.store(num,'-FLAGS','\\Seen')


if __name__ == '__main__':
    main()
