#!/usr/bin/python
#
# Fetch passwords for imap/smtp accounts from gnome-keyring
# Adding passwords to gnome-keyring is up to yourself. Passwords added
# by evolution will be picked up, which may help.
#
# Usage in .muttrc:
# source "~/bin/mutt-keyring $folder $smtp_url|"

import gnomekeyring as gk
import glib
import sys
import urllib
import urlparse
from ConfigParser import ConfigParser
import os

KEYRING_NAME = 'login'

def parse_url(url):
    url = urlparse.urlsplit(url)
    scheme = 'imap' if url.scheme.startswith('imap') else 'smtp'
    username = url.username
    if ';' in username:
        username = username[:username.find(';')]
    if '@' in username:
        username = urllib.quote(username)
    return (scheme, username, url.hostname)

urls = [parse_url(x) for x in sys.argv[1:]]
glib.set_application_name('mutt')

for id in gk.list_item_ids_sync(KEYRING_NAME):
    item = gk.item_get_info_sync(KEYRING_NAME, id)
    name = item.get_display_name()
    url = None
    if name.startswith('Evolution Data Source'):
        attrs = gk.item_get_attributes_sync(KEYRING_NAME, id)
        src = attrs['e-source-uid']
        cp = ConfigParser()
        cp.read(os.path.join(os.path.expanduser('~'), '.config', 'evolution', 'sources', src + '.source'))
        if cp.has_section('Authentication') and cp.has_section('Mail Account'):
            url = ('imap', cp.get('Authentication', 'User'), cp.get('Authentication', 'Host'))
        elif cp.has_section('Authentication') and cp.has_section('Mail Transport'):
            url = ('smtp', cp.get('Authentication', 'User'), cp.get('Authentication', 'Host'))
        elif cp.has_section('Authentication') and cp.has_section('Collection'):
            url = ('imap', urllib.quote(cp.get('Collection', 'Identity')), 'imap.gmail.com')
    if url in urls:
        print "set %s_pass='%s'" % (url[0], item.get_secret())
