#!/usr/bin/env python
"""
The MIT License

Copyright (c) 2008 Mary Gardiner

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
"""

import getpass, imaplib, sys, optparse

import parseNested

IGNORE = set(["INBOX", "Postponed", "Sent", "Sent Items", "Trash", "Drafts"])

def main():
    parser = optparse.OptionParser(usage = "Usage: %prog [options] imap-server username")
    parser.add_option("-p", "--port", dest="port",
                      help="port number to connect to, if not standard", metavar="PORT")
    parser.add_option("-q", "--quiet",
                      action="store_false", dest="verbose", default=True,
                      help="don't print status messages to standard error")
    parser.add_option("-s", "--ssl",
                      action="store_true", dest="ssl", default=False,
                      help="Use SSL encryption")

    (options, args) = parser.parse_args()

    if len(args) != 2:
        parser.error("Incorrect number of arguments: use '--help' for help")
    host = args[0]
    if options.ssl:
        IMAPClass = imaplib.IMAP4_SSL
    else:
        IMAPClass = imaplib.IMAP4
    if options.port:
        try:
            port = int(options.port)
        except ValueError:
            parser.error("Port number must be an integer. Use '--help' for help")
        M = IMAPClass(host, port)
    else:
        M = IMAPClass(host)
    user = args[1]
    M.login(user, getpass.getpass('IMAP password for user %s at server %s: ' % (user, host)))
    listresponse = M.list()
    mailboxes = []
    for chunk in listresponse[1]:
        nested = parseNested.parseNestedParens(chunk)
        if '\\HasNoChildren' in nested[0] and '\\NoSelect' in nested[0]:
            if options.verbose:
                sys.stderr.write("%s has no children and is not selectable, deleting\n" % nested[2])
            M.delete(nested[2])
        elif not '\\HasChildren' in nested[0] and not nested[2] in IGNORE and not "INBOX." + nested[2] in IGNORE:
            mailboxes.append(nested[2])
    for mailbox in mailboxes:
        M.select(mailbox)
        # search for all messages
        typ, data = M.search(None, 'ALL')
        M.close()
        if len(data[0].split()) == 0:
            if options.verbose:
                sys.stderr.write("%s is empty of messages, deleting\n" % mailbox)
            M.delete(mailbox)
    M.logout()

if __name__ == '__main__':
    main()
