#!/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 update infomation about images"""

import os
import sys
import base64
import datetime
sys.path.insert(1, os.path.join(sys.path[0], '..'))

from common.buildtrigger import trigger_info, trigger_next
from common.buildservice import BuildService
from common.trbs import is_trbs_project
from common.iris_rest_client import IrisRestClient
from common.send_mail import prepare_mail
from common.gerrit import Gerrit,GerritError

def send_mail_buildstatus_message(info, project):
    """ send mail about buildstatus """
    EMAIL_TITLE = "[%s][%s][#%s] (Build:%s Images%s)"
    EMAIL_BODY = "OBS Build and Snapshot and Image creator status \n" \
                 "Please check the following details.\n\n" \
                 "Submitter : %s\n\n" \
                 "Reference project : %s\n" \
                 "Git tag : %s\n" \
                 "Git Repository : %s\n" \
                 "Build status : %s\n" \
                 "Image status : %s\n" \
                 "Snapshot url: %s\n\n" \
                 "For more details please check: %s"
    EMAIL_FOOTER = '\n\n--------------------------------------------------------\n'\
                   'Automatically generated by backend service.\n'\
                   'Please DO NOT Reply!'

    #build status
    buildstatus=''
    title_build = 'Succeeded'
    for status in info.get("buildstatus"):
        buildstatus += "\n Repository: %s arch: %s (%s:%s)" \
                       % (status.get('repo'),status.get('arch'), \
                          status.get('code'),status.get('count') \
                         )
        if status.get('code') != 'succeeded':
            title_build = 'Failed'
    buildstatus += '\n'
 
    imgsuccess, imgfailed, imgstatus = 0, 0, ''
    submitters = info['submitter'] or ""
    for image in info['images']:
        imgstatus  += "\n Repository : %s Status : (%s) %s " \
                      % (image['name'], image['status'], image['url'])
        if image['status'] == 'success':
            imgsuccess += 1
        if image['status'] == 'failed':
            imgfailed += 1
    imgstatus += "\n success (%s)  failed (%s) \n" % (imgsuccess, imgfailed)
    if imgfailed == 0:
        title_images = 'Succeeded'
    else:
        title_images = 'Failed'

    obs_url = os.path.join( os.getenv("OBS_URL") , "project/show?project=" + project)

    project=''
    for prj in info['projects']:
        project += '   \n' + prj

    #make a message
    title = EMAIL_TITLE % ("TRBS", info['git_tag'], info['download_num'], \
                           title_build, title_images)
    email_body = EMAIL_BODY % (submitters, \
                               info['obs_target_prj'], \
                               info['git_tag'], \
                               project, \
                               buildstatus, \
                               imgstatus, \
                               info['download_url'], \
                               obs_url)
    msg = 'Hello \n\n' + email_body + EMAIL_FOOTER
    #print title
    #print msg
    submitter = info['submitter']
    #print submitter
    if submitter:
        submitter = "onstudy <onstudy@samsung.com>"
        prepare_mail("%s.env" % os.getenv('BUILD_TAG'), title, msg,
                     os.getenv('NOREPLY_EMAIL_SENDER'), submitter)
    
    if False:
        mygerrit = Gerrit(os.getenv("GERRIT_HOSTNAME"), \
                          os.getenv("GERRIT_USERNAME"), \
                          os.getenv("GERRIT_SSHPORT"))
        try:
            mygerrit.review(commit=info['git_commit'], message=msg)
        except GerritError, err:
            print >> sys.stderr, 'Error posting review comment '\
                                 'back to Gerrit: %s' % str(err)
            # return 1 if this exception is not caused by invalid commit
            if 'no such patch set' not in str(err):
                return False
    return True

def main():
    """The main body"""
    buildmonitor_enabled = os.getenv("BUILDMONITOR_ENABLED", "0") != "0"
    print 'buildmonitor_enabled(%s)\n' % (buildmonitor_enabled)
    if buildmonitor_enabled:
        bm_start_datetime = datetime.datetime.now()

    obs_api = os.getenv("OBS_API_URL")
    obs_user = os.getenv("OBS_API_USERNAME")
    obs_passwd = os.getenv("OBS_API_PASSWD")

    content = trigger_info(os.getenv('TRIGGER_INFO'))

    project = content.get('project', '')
    name = content.get('name')
    status = content.get('status', '')
    url = content.get('url', '')
    # add image_created log for iris
    pub_enabled = os.getenv("IRIS_PUB_ENABLED", "0") != "0"
    if pub_enabled:
        rest = IrisRestClient(
            os.getenv("IRIS_SERVER"),
            os.getenv("IRIS_USERNAME"),
            base64.b64decode(os.getenv('IRIS_PASSWORDX', '')))
        rest.publish_event("image_created", {
        "project": project,
        "status": status,
        "name": name,
        "url": url,
        })

    # If the project is trbs project, trigger the post-image-creation
    if is_trbs_project(project):
        build = BuildService(obs_api, obs_user, obs_passwd)

        saveinfo = build.get_info(project)
        if saveinfo.get('download_num', 0) != content.get('download_num', 1):
            print 'EXCEPTION* mismatch download_num current:%s, obs:%s' \
                  % (content.get('download_num'), saveinfo.get('download_num'))
            print 'SKIP UPDATING BUILD INFO'
            return

        info = {"images":
                    [{"name": name,
                     "status": status,
                     "url": url}]
                }
        build.update_info(info, project)

        try:
            saveinfo = build.get_info(project)
            print "images count : %s %s \n" % ( len(saveinfo['images']), saveinfo['images_count'])
            if len(saveinfo['images']) == int(saveinfo['images_count']):
                # send mail to submitter
                #send_mail_buildstatus_message(saveinfo,project)

                # trigger next 
                trigger_next('TEST-AUTOMATION', saveinfo) 
				
            if buildmonitor_enabled:
                if len(saveinfo['images']) == saveinfo['images_count']:
                    print '[%s] last image(%s)\n' \
                          % (__file__, len(saveinfo['images']))
                    #buildmonitor.end_create_image_for_sr_stage(bm_start_datetime,
                    #                                           project)
                    bm_stage = 'Post_Image'
                    bm_data = {"bm_stage" : bm_stage,
                               "bm_start_datetime" : str(bm_start_datetime),
                               "project" : project,
                              }
                    trigger_next("BUILD-MONITOR", bm_data)
        except:
            print 'exception images_count'
            if buildmonitor_enabled:
                print '[%s] last image(%s)\n' \
                      % (__file__, len(saveinfo['images']))
                #buildmonitor.end_create_image_for_sr_stage(bm_start_datetime,
                #                                           project)
                bm_stage = 'Post_Image'
                bm_data = {"bm_stage" : bm_stage,
                           "bm_start_datetime" : str(bm_start_datetime),
                           "project" : project,
                          }
                trigger_next("BUILD-MONITOR", bm_data)

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