#!/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

from time import sleep
from common.buildtrigger import trigger_info, trigger_next
from common.buildservice import BuildService
from common.prerelease import is_prerelease_project
from common.iris_rest_client import IrisRestClient

# set default char-set endcoding to utf-8
reload(sys)
sys.setdefaultencoding('utf-8') # pylint: disable-msg=E1101

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', '')
    build_id = content.get('build_id', '')
    repo = content.get('repo', '')
    # 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 prerelease project, trigger the post-image-creation
    if is_prerelease_project(project):
        build = BuildService(obs_api, obs_user, obs_passwd)

        # get env
        if not os.getenv("POST_IMAGE_POLL_CNT") or not os.getenv("POST_IMAGE_POLL_SEC"):
            print '[%s] POST_IMAGE_POLL_CNT or POLL_SEC does not exist!!\n' % (__file__)
            poll_cnt = int(3)
            poll_sec = int(10)
        else:
            poll_cnt = int(os.getenv("POST_IMAGE_POLL_CNT"))
            poll_sec = int(os.getenv("POST_IMAGE_POLL_SEC"))
        print '[%s] poll_cnt(%s), poll_sec(%s)\n' \
              % (__file__, poll_cnt, poll_sec)

        # do polling
        while poll_cnt > 0:
            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,
                          "repo": repo,
                          "url": url}]
                   }

            before_update_img_cnt = len(saveinfo['images'])
            build.update_info(info, project)

            # for check
            checkinfo = build.get_info(project)
            after_update_img_cnt = len(checkinfo['images'])
            target_img_cnt = saveinfo['images_count']
            print '[%s] before_update_img_cnt(%s), after_update_img_cnt(%s) / target_img_cnt(%s)\n' \
                  % (__file__, before_update_img_cnt, after_update_img_cnt, target_img_cnt)
            poll_cnt -= 1

            if after_update_img_cnt == target_img_cnt:
                print '[%s] reached the target_img_cnt(%s)!! trigger BUILD-MONITOR(Post_Image)\n' \
                      % (__file__, target_img_cnt)

                # check whether the image status is failed or not
                skip_test_trigger = False
                for each_item in checkinfo["images"]:
                    if each_item["status"] == "failed":
                        skip_test_trigger = True
                        print 'name:%s, status:%s' % (each_item["name"], each_item["status"])

                if not skip_test_trigger:
                    trigger_next("TEST-TRIGGER-INFO-UPDATE", checkinfo)
                else:
                    print 'skip_test_trigger!!\n'

                # NOTIFY BUILDSTATUS
                trigger_next("NOTIFY-BUILDSTATUS", checkinfo)

                if buildmonitor_enabled:
                    #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,
                               "bm_snapshot_name" : build_id,
                              }
                    trigger_next("BUILD-MONITOR", bm_data)
                break
            elif before_update_img_cnt == after_update_img_cnt:
                print '[%s] update_info failed!! wait %s sec, remaining poll_cnt is (%s)\n' \
                      % (__file__, poll_sec, poll_cnt)
                sleep(poll_sec)
                continue
            else:
                print '[%s] update_info succeeded!! keep going\n' % (__file__)
                break

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