#!/usr/bin/env python
#
# Copyright (C) 2010, 2011, 2012, 2013, 2014 Intel, Inc.
#
#    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; version 2
#    of the License.
#
#    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., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
#
"""This script is used to send mail due to job's finishing state"""

import os
import base64
import sys

from common.send_mail import sendmail, MailError

def main():
    """The main body"""

    # quit send mail if silent_mode set
    if int(os.getenv('GERRIT_SILENT_MODE')):
        return

    try:
        msg = base64.b64decode(os.getenv('MESSAGE'))
    except TypeError:
        print "Invalid mail message, job aborted!"
        return 1
    else:
        fromaddr = os.getenv('FROM')
        toaddr = os.getenv('TO')
        smtp_server = os.getenv('SMTP_SERVER')
        if not fromaddr or not toaddr or not smtp_server:
            print "Error: configuration parameters 'FROM', 'TO' "\
                  "or 'SMTP_SERVER' are not set"
            return 1
        try:
            sendmail(fromaddr, toaddr.split(','), msg, smtp_server)
        except MailError, err:
            print 'Email from %s to %s' % (fromaddr, toaddr.split(','))
            print err
            return 1

if __name__ == '__main__':
    sys.exit(main())
