#! /usr/bin/env python
"""
-------------------------------------------------------------------------------
Copyright (C) 2005, 2006  Sylvain Fourmanoit

Released under the GPL, version 2.

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 of the Software and its documentation and acknowledgment shall be
given in the documentation and software packages that this Software was
used.

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 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.
-------------------------------------------------------------------------------
This is the adesklet's desklet submission script. Have a look at adesklets
documentation for details.
"""
#------------------------------------------------------------------------------
import getopt
import urllib
import smtplib
from email import Encoders
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
from email.MIMEImage import MIMEImage
from email.MIMEBase import MIMEBase
from pprint import PrettyPrinter
from sys import argv, exit, stderr
from os import getenv
from os.path import join

#------------------------------------------------------------------------------
# Print usage function
#
def usage(msg=None):
    print 'Usage: %s [--help] [--send] desklet_name' % argv[0],"""
    desklet_name - name of the desklet

See official adesklets documentation for usage details
"""
    if msg: print 'Error:', msg
    exit(1)

#------------------------------------------------------------------------------
# Read in the configuration
#
config_name=join(getenv('HOME'),'.adesklets_submit')
try:
    f = file(config_name,'r')
except IOError:
    usage("Could not read '%s' configuration file" % config_name)
config={}; exec f in config; del config['__builtins__']
f.close()

#------------------------------------------------------------------------------
# Determine what to do by looking at the command line
#
try:
    opts, args = getopt.getopt(argv[1:],'',['send', 'help'])
    opts=dict(opts)
except getopt.GetoptError,(errno, strerror):
    usage(errno)
if opts.has_key('--help'): usage()
if len(args)==0: usage('desklet name not given')

#------------------------------------------------------------------------------
# Verify we are looking at an existing package
#
if not config['desklets'].has_key(args[0]):
    raise KeyError("Given desklet entry '%s' does not exist" % args[0])

#------------------------------------------------------------------------------
# Get the three files for thumbnail, screenshot and download
#
def getfile(key):
    try:
         f=file(join(getenv('HOME'),
                     config['desklets'][args[0]][key]),'r')
    except:
        try:
            f=urllib.urlopen(config['desklets'][args[0]][key])
        except:
            f = None
    return f
files = dict([(name,getfile(name)) for name in
              ['thumbnail','screenshot','download']])
if not files['download']:
    raise IOError('Package file could not be found.')

#------------------------------------------------------------------------------
# Build the email body
#
# First, the enveloppe
#
msg = MIMEMultipart()
msg['Subject'] = 'New desklet: ' + args[0] 
msg['From'] = '%s <%s>' % (config['info']['author_name'],
                           config['info']['author_email'])
recip = ['adesklets@mailworks.org']        # Do not use this address
                                           # for anything else, it is useless:
                                           # everything not conforming to this
                                           # will be dropped without human
                                           # intervention.
msg['To'] = 'S.Fourmanoit <%s>' % recip[0]
if config['cc_to_self']:
    msg['Cc'] = '%s <%s>' % (config['info']['author_name'],
                             config['info']['author_email'])
    recip.append(config['info']['author_email'])
msg.epilogue = ''

# Then the textual message
#
config['desklets'][args[0]]['name']=args[0]
pp = PrettyPrinter(width=70)
msg.attach(MIMEText('%s\n\n%s' % (
    'info = ' + pp.pformat(config['info']),
    'desklet = ' + pp.pformat(config['desklets'][args[0]]))))

# Then the images
#
for image in [files['thumbnail'], files['screenshot']]:
    if image.__class__==file:
        msg.attach(MIMEImage(image.read()))

# Finally, the desklet tarball
#
if files['download'].__class__==file:
    payload = MIMEBase('application','octet-stream')
    payload.set_payload(files['download'].read())
    Encoders.encode_base64(payload)
    msg.attach(payload)
else:
    if not files['download']:
        raise IOError('Could not retrieve desklet package')

#------------------------------------------------------------------------------
# Last step: we choose between sending the message, or keeping it
# for ourselves, depending of user choice and size.
#
size=len(msg.as_string())/1024
if size>300:
    raise IOError('Message is %d KB - too big.' % size + 
                  'Attach content as url.' % size)
if not opts.has_key('--send'):
    print msg.as_string()
else:
    s=smtplib.SMTP(config['smtp_host'],config['smtp_port'])
    s.sendmail(config['info']['author_email'],
               recip,
               msg.as_string())
    s.close()
