# -*- python -*-
# -*- coding: utf-8 -*-
#
# Copyright (C) 2007, 2008 by Jan Dittberner.
#
# 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, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
# USA.
#
# Version: $Id$

"""GPG mail handling.

This module provides functionallity for sending signed and encrypted
email using GnuPG.
"""

import smtplib
from email.MIMEText import MIMEText
from pyme import core
from pyme.constants.sig import mode

from gnuviechadmin.backend.settings import config

def send_mail(subject, text):
    """Send a signed and possibly encrypted mail.

    This method sends a mail with the given text and subject and signs
    it using GnuPG. If a public key of the recipient is available the
    mail is encrypted. The sender and recipient addresses are taken
    from the configuration (section: common, properties: mailfrom,
    mailto)

    Arguments:
    subject -- mail subject
    text -- mail text
    """
    if not text.__class__.__name__ == 'str':
        text = text.encode('ascii', 'replace')
    plain = core.Data(text)
    cipher = core.Data()
    c = core.Context()
    c.set_armor(1)
    signer = config.get('common', 'mailfrom')
    rcpt = config.get('common', 'mailto')
    c.signers_clear()
    for sigkey in [x for x in c.op_keylist_all(signer, 1)]:
      if sigkey.can_sign:
        c.signers_add(sigkey)
      if not c.signers_enum(0):
        raise Exception("No secret keys for signing available for %s." % (
          signer))
    keylist = []
    for key in c.op_keylist_all(rcpt, 0):
      valid = 0
      subkey = key.subkeys
      while subkey:
        keyid = subkey.keyid
        if keyid == None:
          break
        can_encrypt = subkey.can_encrypt
        valid += can_encrypt
        subkey = subkey.next
      if valid:
        keylist.append(key)
    if keylist:
      c.op_encrypt_sign(keylist, 1, plain, cipher)
    else:
      c.op_sign(plain, cipher, mode.CLEAR)
    cipher.seek(0,0)

    msg = MIMEText(cipher.read())
    if keylist:
      msg.set_param("x-action", "pgp-encrypted")
    msg['Subject'] = subject
    msg['From'] = signer
    msg['To'] = rcpt

    s = smtplib.SMTP()
    s.connect()
    s.sendmail(signer, [rcpt], msg.as_string())
    s.close()