bh@99: #! /usr/bin/python2.4
bh@99: # Copyright (C) 2008 by Intevation GmbH
bh@99: # Authors:
bh@99: # Bernhard Herzog <bh@intevation.de>
bh@99: #
bh@99: # This program is free software under the GPL (>=v2)
bh@99: # Read the file COPYING coming with the software for details.
bh@99: 
bh@99: """Send pending notification mails"""
bh@99: 
bh@99: import os
bh@99: import smtplib
bh@99: import email
bh@99: import email.Utils
bh@99: from optparse import OptionParser
bh@99: from ConfigParser import SafeConfigParser
bh@99: 
bh@99: import treepkgcmd
bh@99: from treepkg.readconfig import read_config_section
bh@99: from treepkg.run import capture_output
bh@99: from treepkg.cmdexpand import cmdexpand
bh@99: 
bh@99: notification_desc = ["build_user", "build_host", "build_listpending",
bh@100:                      "notification_template",
bh@99:                      "smtp_host", ("smtp_port", int),
bh@99:                      ]
bh@99: 
bh@99: def read_config(filename):
bh@99:     parser = SafeConfigParser()
bh@99:     parser.read([filename])
bh@99:     return read_config_section(parser, "notification", notification_desc)
bh@99: 
bh@99: def parse_commandline():
bh@99:     parser = OptionParser()
bh@99:     parser.set_defaults(config_file=os.path.join(treepkgcmd.topdir,
bh@99:                                                  "notification.cfg"))
bh@99:     parser.add_option("--config-file",
bh@99:                       help=("The configuration file."
bh@99:                             " Default notification.cfg"))
bh@99:     return parser.parse_args()
bh@99: 
bh@99: 
bh@99: def send_mail(config, raw_message):
bh@99:     msg = email.message_from_string(raw_message)
bh@99:     sender = email.Utils.parseaddr(msg["From"])[1]
bh@99:     recipients = [addr[1] for addr
bh@99:                   in email.Utils.getaddresses(msg.get_all("To", [])
bh@99:                                               + msg.get_all("Cc", []))]
bh@99:     server = smtplib.SMTP(config["smtp_host"], config["smtp_port"])
bh@99:     server.sendmail(sender, recipients, raw_message)
bh@99:     server.quit()
bh@99: 
bh@99: 
bh@99: def send_notification_mails(config_filename):
bh@99:     config = read_config(config_filename)
bh@99: 
bh@99:     template = open(config["notification_template"]).read()
bh@99: 
bh@99:     lines = capture_output(cmdexpand("ssh $build_user$@$build_host"
bh@99:                                      " $build_listpending",
bh@99:                                      **config))
bh@99:     for line in lines.splitlines():
bh@99:         words = line.split()
bh@99:         if len(words) == 3:
bh@99:             status, track, revision = words
bh@99:             values = config.copy()
bh@99:             values.update(locals())
bh@99:             send_mail(config, template % values)
bh@99: 
bh@99: 
bh@99: def main():
bh@99:     options, args = parse_commandline()
bh@99:     send_notification_mails(options.config_file)
bh@99: 
bh@99: main()