#!/usr/bin/env python
# vim: ai ts=4 sts=4 et sw=4
#
# 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 code is called by jenkins jobs triggered by OBS events.
"""

import os
import sys
import re
import datetime

from common.repomaker import RepoMaker, RepoMakerError
from common.buildtrigger import trigger_info, trigger_next
from common.buildservice import BuildService
from common.backenddb import BackendDB
from common.snapshot import Snapshot, SnapshotError, snapshot_project_enabled
from common.utils import make_latest_link, sync
from common.send_mail import prepare_mail
from common.manifest import get_build_id_from_build_xml

class LocalError(Exception):
    """Local error exception."""
    pass


def prepare_trigger_data(images, build_id, path_repo, project,
                           url_pub_base):
    """
    prepare_trigger_data:
        Prepare the trigger data
    Args:
         images_ks (truple list): [(ks_file_name, ks_file_content),]
         build_id (str): the prerelease repo build_id
    """
    download_host = os.getenv('DOWNLOAD_HOST')
    trigger_data = {} #trigger job_imager
    trigger_snapdiff = {}

    for repo_name in images:
        trigger_data[repo_name] = []
        trigger_snapdiff[repo_name] = []
        for ksname, kickstart in images[repo_name].ksi.items():
            name = ksname.replace('.ks', '')
            if download_host:
                # replace host name
                kickstart = re.sub('^(repo .*--baseurl=[^:]+://)[^/]+(/.*)',
                                   '\\1%s\\2' % download_host, kickstart,
                                   count=1, flags=re.MULTILINE)
            data = {'name': name,
                    'kickstart': kickstart,
                    'buildid': build_id,
                    'images_path': os.path.join("images", repo_name, name),
                    'project': project,
                    'repo': repo_name,
                    'repo_path': path_repo,
                    'url_pub_base': url_pub_base
                    }

            data['base_config'] = ''
            try:
                for line in kickstart.splitlines():
                    if not line.startswith('repo ') or 'baseurl=' not in line or '@BUILD_ID@' in line:
                        continue
                    match = re.match(r"repo --name=base([\w\-\.]*) --baseurl=(.*/repos/.*) .*", line)
                    if match and match.groups() and len(match.groups()) == 2:
                        base_arch, base_repo_url = match.groups()
                        data['base_config'] = base_repo_url
            except Exception as err:
                print repr(err)

            trigger_data[repo_name].append(data)
            data_snapdiff = data.copy()
            data_snapdiff.pop('kickstart')
            trigger_snapdiff[repo_name].append(data_snapdiff)

    return trigger_data, trigger_snapdiff

def trigger_image_creation(trigger_data):
    """Trigger the image_creation jobs"""
    count = 0
    for repo in trigger_data.keys():
        for index, data in enumerate(trigger_data[repo]):
            trigger_next('image_trigger_%s_%s' % (repo, index), data, show=False)
            count += 1
    # Request number of imager nodes
    if os.getenv("ONDEMAND_SLAVE_CONFIGURATION_ENABLED", "0") == "1":
        if count > 0:
            trigger_next("SLAVE_BUILDER", {"data":"dummy"}, \
                         extra_params={"ACTION": "REQUEST_WORKER", \
                                       "PURPOSE": "JENKINS_IMAGER", \
                                       "REQUESTED_NUM_EXECUTORS": "%d" % count})

def make_live_sync_repo(project, backenddb, base_path, live_repo_base):
    """
    make live sync repo.
    """

    try:
        snapshot = Snapshot(backenddb, base_path, obs_project=project)

        # Increment snapshot
        snapshot.inc()

        # Store variables into local rather than accessing Snapshot() instance.
        local_build_id = snapshot.build_id
        local_targets  = snapshot.targets
        local_path     = snapshot.path
        local_dir      = snapshot.dir

        # Delete Snapshot() instance.
        del snapshot

        print 'We are working on live:'
        print '\t%s\n\t%s\n\t%s\n\t%s\n\n' % (local_build_id, local_targets, local_path, local_dir)
        sys.stdout.flush()
    except SnapshotError, err:
        raise LocalError("Error getting snapshot info: %s" % str(err))

    if buildmonitor_enabled:
        bm_snapshot_name = local_build_id
        bm_stage = 'Post_Snap_snapshot'
        bm_data = {"bm_stage" : bm_stage,
                   "project" : project,
                   "bm_snapshot_name" : bm_snapshot_name,
                   "bm_start_datetime" : str(bm_start_datetime)
                  }
        trigger_next("BUILD-MONITOR-2-%s" % bm_stage, bm_data)


    live_repo_path = os.path.join(live_repo_base,
                                  project.replace(':', ':/'))
    repos = {}
    imagedatas = {}

    # sync snapshot to release
    sync(live_repo_path, local_path, remove=False, hardlinks=True)

    if buildmonitor_enabled:
        targets = local_targets
        for repo in targets:
            bm_repo = repo['Name']
            bm_arch = repo['Architectures'][0]
            if bm_arch == 'ia32':
                bm_arch = 'i686'

            bm_repo_dir = os.path.join(local_path, bm_repo)
            bm_base_url = os.getenv("URL_PUBLIC_REPO_BASE")
            bm_pkg_url = bm_repo_dir.replace(base_path, bm_base_url)
            bm_pkg_name_lst = []
            bm_pkg_mdate_lst = []
            bm_pkg_size_lst = []
            bm_trg_count = 0
            bm_pkg_count = 0
            BM_PKG_LIMIT = 1100
            for root, dirs, files in os.walk(bm_repo_dir):
                for each_file in files:
                    if each_file.endswith(".rpm") or each_file.endswith(".deb"):
                        rpm_file_path = os.path.join(root, each_file)
                        rpm_file_mdate = os.path.getmtime(rpm_file_path)
                        rpm_file_size = os.path.getsize(rpm_file_path)
                        bm_pkg_name_lst.append(each_file)
                        bm_pkg_mdate_lst.append(rpm_file_mdate)
                        bm_pkg_size_lst.append(rpm_file_size)
                        bm_pkg_count += 1
                        if bm_pkg_count >= BM_PKG_LIMIT:
                            # for trigger
                            bm_stage = 'Post_Snap_packages'
                            bm_data = {"bm_stage" : bm_stage,
                                       "bm_snapshot_name" : bm_snapshot_name,
                                       "bm_repo" : bm_repo,
                                       "bm_arch" : bm_arch,
                                       "bm_pkg_url" : bm_pkg_url,
                                       "bm_pkg_name_lst" : bm_pkg_name_lst,
                                       "bm_pkg_mdate_lst" : bm_pkg_mdate_lst,
                                       "bm_pkg_size_lst" : bm_pkg_size_lst,
                                      }
                            trigger_next("BUILD-MONITOR-3-%s-%s-%s-%s" % \
                                    (bm_stage, bm_repo, bm_arch, bm_trg_count), bm_data, show=False)

                            # clear the data
                            bm_pkg_count = 0
                            bm_trg_count += 1
                            bm_pkg_name_lst = []
                            bm_pkg_mdate_lst = []
                            bm_pkg_size_lst = []
            bm_stage = 'Post_Snap_packages'
            bm_data = {"bm_stage" : bm_stage,
                       "bm_snapshot_name" : bm_snapshot_name,
                       "bm_repo" : bm_repo,
                       "bm_arch" : bm_arch,
                       "bm_pkg_url" : bm_pkg_url,
                       "bm_pkg_name_lst" : bm_pkg_name_lst,
                       "bm_pkg_mdate_lst" : bm_pkg_mdate_lst,
                       "bm_pkg_size_lst" : bm_pkg_size_lst,
                       "bm_trg_count" : bm_trg_count,
                       "bm_pkg_count" : bm_pkg_count,
                       "BM_PKG_LIMIT" : BM_PKG_LIMIT,
                      }
            trigger_next("BUILD-MONITOR-3-%s-%s-%s-trg_%s" % \
                    (bm_stage, bm_repo, bm_arch, bm_trg_count), bm_data, show=False)

    return {'project': project,
            'repo': repos,
            'repo_path': os.path.join(local_dir, local_build_id),
            'build_id': local_build_id,
            'imagedata': imagedatas,
            'duplicated': "",
            'manifestdata': "",
            }

def make_repo(project, backenddb, base_path, live_repo_base, base_id=None, ref_id=None):
    """
    make repo.

    Args:
        project (str): OBS prerelease project name
        repo (str): name of the OBS live repository
        backenddb (BackendDB): backenddb instance
        base_path (str): path to the location of snapshot
        live_repo_base (str): path to live repo
    Raises:
        LocalError if can't create repos or can't find image configurations
    """

    try:
        snapshot = Snapshot(backenddb, base_path, obs_project=project)

        # Increment snapshot
        snapshot.inc()

        # Store variables into local rather than accessing Snapshot() instance.
        local_build_id = snapshot.build_id
        local_targets  = snapshot.targets
        local_path     = snapshot.path
        local_dir      = snapshot.dir

        # Delete Snapshot() instance.
        del snapshot

        print 'We are working on:'
        print '\t%s\n\t%s\n\t%s\n\t%s\n\n' % (local_build_id, local_targets, local_path, local_dir)
        sys.stdout.flush()
    except SnapshotError, err:
        raise LocalError("Error getting snapshot info: %s" % str(err))


    targets = local_targets
    live_repo_path = os.path.join(live_repo_base,
                                  project.replace(':', ':/'))
    repos = {}
    imagedatas = {}
    duplicated_report = []
    manifesttemp = []
    manifestdata = []

    if buildmonitor_enabled:
        bm_snapshot_name = local_build_id
        #buildmonitor.start_create_snapshot_for_post_build_snapshot(project,
        #                                                           bm_snapshot_name,
        #                                                           bm_start_datetime)
        bm_stage = 'Post_Snap_snapshot'
        bm_data = {"bm_stage" : bm_stage,
                   "project" : project,
                   "bm_snapshot_name" : bm_snapshot_name,
                   "bm_start_datetime" : str(bm_start_datetime)
                  }
        trigger_next("BUILD-MONITOR-2-%s" % bm_stage, bm_data)

    # Convert live repo to download structure
    for repo in targets:
        repomaker = RepoMaker(local_build_id, local_path)

        # Get specific repo buildconf from OBS, put the buildconf together with
        # repo-md
        build = BuildService(os.getenv("OBS_API_URL"),
                             os.getenv("OBS_API_USERNAME"),
                             os.getenv("OBS_API_PASSWD"))
        buildconf = build.get_repo_config(project, repo['Name'])

        try:
            repomaker.add_repo(live_repo_path, repo['Name'],
                               repo['Architectures'],
                               buildconf=buildconf, move=False)
        except RepoMakerError, err:
            raise LocalError("Unable to create download repo: %s" % err)

        if not repomaker.imagedata:
            if buildmonitor_enabled:
                print '[%s][LocalError] bm_project(%s)\n' % (__file__, bm_project)
                #buildmonitor.update_fail_create_snapshot_for_sr_stage(bm_project)
                bm_stage = 'Post_Snap_Fail'
                bm_data = {"bm_stage" : bm_stage,
                           "bm_snapshot_name" : local_build_id,
                          }
                trigger_next("BUILD-MONITOR-5-%s" % bm_stage, bm_data)
            raise LocalError("Image configuration not found in %s" %
                             local_path)

        repos.update(repomaker.repos)
        imagedatas[repo['Name']] = repomaker.imagedata

        if buildmonitor_enabled:
            bm_repo = repo['Name']             # emul32-wayland / emul64-wayland / arm-wayland / arm64-wayland / target-TM1
            bm_arch = repo['Architectures'][0] # ia32 / x86_64 / armv7l / aarch64 / armv7l
            if bm_arch == 'ia32':
                bm_arch = 'i686'

            bm_repo_dir = os.path.join(local_path, "repos", bm_repo, "packages")
            bm_base_url = os.getenv("URL_PUBLIC_REPO_BASE")
            bm_pkg_url = bm_repo_dir.replace(base_path, bm_base_url)
            bm_pkg_name_lst = []
            bm_pkg_mdate_lst = []
            bm_pkg_size_lst = []
            bm_trg_count = 0
            bm_pkg_count = 0
            BM_PKG_LIMIT = 1100
            for root, dirs, files in os.walk(bm_repo_dir):
                for each_file in files:
                    if each_file.endswith(".rpm"):
                        rpm_file_path = os.path.join(root, each_file)
                        rpm_file_mdate = os.path.getmtime(rpm_file_path)
                        rpm_file_size = os.path.getsize(rpm_file_path)
                        bm_pkg_name_lst.append(each_file)
                        bm_pkg_mdate_lst.append(rpm_file_mdate)
                        bm_pkg_size_lst.append(rpm_file_size)
                        bm_pkg_count += 1
                        if bm_pkg_count >= BM_PKG_LIMIT:
                            # for trigger
                            bm_stage = 'Post_Snap_packages'
                            bm_data = {"bm_stage" : bm_stage,
                                       "bm_snapshot_name" : bm_snapshot_name,
                                       "bm_repo" : bm_repo,
                                       "bm_arch" : bm_arch,
                                       "bm_pkg_url" : bm_pkg_url,
                                       "bm_pkg_name_lst" : bm_pkg_name_lst,
                                       "bm_pkg_mdate_lst" : bm_pkg_mdate_lst,
                                       "bm_pkg_size_lst" : bm_pkg_size_lst,
                                      }
                            trigger_next("BUILD-MONITOR-3-%s-%s-%s-%s" % (bm_stage, bm_repo, bm_arch, bm_trg_count), bm_data, show=False)

                            # clear the data
                            bm_pkg_count = 0
                            bm_trg_count += 1
                            bm_pkg_name_lst = []
                            bm_pkg_mdate_lst = []
                            bm_pkg_size_lst = []
            bm_stage = 'Post_Snap_packages'
            bm_data = {"bm_stage" : bm_stage,
                       "bm_snapshot_name" : bm_snapshot_name,
                       "bm_repo" : bm_repo,
                       "bm_arch" : bm_arch,
                       "bm_pkg_url" : bm_pkg_url,
                       "bm_pkg_name_lst" : bm_pkg_name_lst,
                       "bm_pkg_mdate_lst" : bm_pkg_mdate_lst,
                       "bm_pkg_size_lst" : bm_pkg_size_lst,
                       "bm_trg_count" : bm_trg_count,
                       "bm_pkg_count" : bm_pkg_count,
                       "BM_PKG_LIMIT" : BM_PKG_LIMIT,
                      }
            trigger_next("BUILD-MONITOR-3-%s-%s-%s-trg_%s" % (bm_stage, bm_repo, bm_arch, bm_trg_count), bm_data, show=False)

        # Generate image info to builddata/ dir
        repomaker.gen_image_info()

        # Generate repo manifest
        manifest_items = repomaker.gen_manifest_info(repo['Name'],
                                    os.getenv('GERRIT_FETCH_URL'),
                                    os.getenv('GERRIT_REVIEW_URL'))
        repomaker.gen_manifest_info_app_from_rpm(repo['Name'],
                                    os.getenv('GERRIT_FETCH_URL'),
                                    os.getenv('GERRIT_REVIEW_URL'),
                                    live_repo_path, repo['Architectures'])
        
        # Add Manifest data
        manifesttemp.extend(list(set([ (t.keys()[0],t[t.keys()[0]][0], t[t.keys()[0]][1]) for t in manifest_items])))
        manifestdata = list(set(manifesttemp))
        # Check duplicated items

        manifest_items_no_pkg_name = []
        for m in manifest_items:
            if {m.keys()[0]: m[m.keys()[0]][0]} in manifest_items_no_pkg_name:
                continue
            manifest_items_no_pkg_name.append({m.keys()[0]: m[m.keys()[0]][0]})
        path_list = [ t.keys()[0] for t in manifest_items_no_pkg_name if t.keys()[0] ]
        duplicated = set([x for x in path_list if path_list.count(x) > 1])
        duplicated_report.extend(list(duplicated))
        #if len(duplicated) >= 1:
        #    prepare_mail('error_report_manifest.env', \
        #                 'Snapshot %s have duplicated packages' % (local_build_id), \
        #                 '\nDuplicated items: %s' % duplicated, \
        #                 os.getenv('NOREPLY_EMAIL_SENDER'), \
        #                 os.getenv('MAILINGLIST_SYSTEM').split(','))

    # Update base id and ref id of the builddata.
    if base_id or ref_id:
        try:
            repomaker = RepoMaker(local_build_id, local_path)
            repomaker.update_extend_builddata(base_id, ref_id)
        except Exception as err:
            print err

    return {'project': project,
            'repo': repos,
            'repo_path': os.path.join(local_dir, local_build_id),
            'build_id': local_build_id,
            'imagedata': imagedatas,
            'duplicated': duplicated_report,
            'manifestdata': manifestdata,
        }

def main(action):
    """Script entry point."""

    print '---[JOB STARTED: %s ]-------------------------'
    global buildmonitor_enabled
    buildmonitor_enabled = os.getenv("BUILDMONITOR_ENABLED", "0") != "0"
    print 'buildmonitor_enabled(%s)\n' % (buildmonitor_enabled)
    if buildmonitor_enabled:
        global bm_start_datetime
        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")
    base_url = os.getenv("URL_PUBLIC_REPO_BASE")
    base_path = os.getenv('PATH_REPO_BASE')
    live_repo_base = os.getenv('PATH_LIVE_REPO_BASE')

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

    project = content.get("project")

    if action == "latest_link":
        # update/create the latest repo link
        print 'make_latest_link'
        make_latest_link(os.path.join(content.get("base_path"), content.get("repo_path")))
        # TRIGGER NEXT RSYNC-DOWNLOAD (MIRROR)
        if os.getenv("RSYNC_DOWNLOAD_ENABLED", "0") != "0":
            trigger_next('RSYNC_DOWNLOAD', content)
        return

    build = BuildService(obs_api, obs_user, obs_passwd)

    unresolvable_broken_packages = {}
    BuildFailReason = 'Succeeded'

    if buildmonitor_enabled:
        global bm_project # for update_fail_xxx

        unresolvable_broken_packages =  build.get_package_build_result(project, ["unresolvable", "broken", "failed"])

        if content.get('build_cycle_check', 0) == 1:
            try:
                cycle_packages = build.cycle_build_added_for_link_project(project, None)
                if cycle_packages is not None:
                    print 'Cycle build detected. %s \n' % cycle_packages
                    BuildFailReason = 'cycles'
                    # Update cycle info
                    for cp_repo in cycle_packages:
                        for cp_item in cycle_packages[cp_repo]:
                            for cp_pkg in cp_item.get('cycles'):
                                unresolvable_broken_packages[cp_repo][cp_item.get('arch')][cp_pkg] = 'cycle'
            except Exception as err:
                print repr(err)

        bm_project = project
        #buildmonitor.start_create_snapshot_for_sr_stage(project, bm_start_datetime)
        bm_stage = 'Post_Snap_Start'
        bm_data = {"bm_stage" : bm_stage,
                   "project" : project,
                   "BuildFailReason" : BuildFailReason,
                   "bm_start_datetime" : str(bm_start_datetime),
                   "unresolvable_broken_packages": unresolvable_broken_packages
                  }
        trigger_next("BUILD-MONITOR-1-%s" % bm_stage, bm_data, show=False, compress=True)

    # Get link project
    ref_project_id = None
    try:
        ref_project_id = build.get_link_project_info(project)
        if ref_project_id:
            l_project = ref_project_id
            loop_count = 10
            while loop_count >= 0:
                l_project = build.get_link_project_info(l_project)
                if l_project == None:
                    break
                else:
                    ref_project_id = l_project
                    loop_count -= 1
        print "ref Project:",ref_project_id
    except Exception as err:
        ref_project_id = None
        print "ref Project is None"

    # Init backend database
    redis_host = os.getenv("REDIS_HOST")
    redis_port = int(os.getenv("REDIS_PORT"))
    backenddb = BackendDB(redis_host, redis_port)

    # Find base project or base release id
    base_release_id = None
    old_base_project = None
    try:
        base_projects = build.get_path_project(project)
        if base_projects:
            old_base_project = base_project = base_projects[0]
            old_base_project += ","
            repo_name = backenddb.get_obs_repo_map()[base_project]
            release_name = backenddb.get_repos()[repo_name]['Release']
            release_id = backenddb.get_release_ids()[repo_name]
            base_release_id = "%s_%s" %(release_name, release_id)
            print 'base release id:',base_release_id
    except Exception as err:
        loop_count = 10
        while loop_count >= 0:
            base_projects = build.get_path_project(base_project)
            if base_projects:
                base_project = base_projects[0]
                old_base_project += base_project
                old_base_project += ","
                print base_project
                loop_count -= 1
            else:
                base_release_id = old_base_project
                break
        print 'base release id is',base_release_id

    if project in backenddb.get_obs_repo_map() and \
       backenddb.get_repos()[backenddb.get_obs_repo_map()[project]] and \
       'LiveSnapshot' in backenddb.get_repos()[backenddb.get_obs_repo_map()[project]]:
        repo_data = make_live_sync_repo(project, backenddb, base_path, live_repo_base)
    else:
        repo_data = make_repo(project, backenddb, base_path, live_repo_base, \
                              base_release_id, ref_project_id)

    # update/create the latest repo link
    #make_latest_link(os.path.join(base_path, repo_data['repo_path']))
    trigger_next("LATEST_LINK", {"base_path" : base_path,
                                 "repo_path" : repo_data['repo_path'],
                                 "project": project,
                                })

    # prepare trigger data for image creation jobs and snapdiff sync jobs
    trigger_data, trigger_snapdiff = prepare_trigger_data(
                                        repo_data['imagedata'],
                                        repo_data['build_id'],
                                        repo_data['repo_path'],
                                        project, base_url)

    # trigger image creation jobs
    trigger_image_creation(trigger_data)

    # trigger snapdiff sync
    for index, repo in enumerate(trigger_snapdiff.keys()):
        trigger_next('snapdiff-trigger_%s' %
                      index, {repo: trigger_snapdiff[repo]})

    # trigger post snapshot creation job with repo data
    data = repo_data.copy()
    # remove unused item
    data.pop('imagedata')
    # add download_url
    data['download_url'] = os.path.join(base_url, data['repo_path'])
    #INSERT MANIFEST DATA TO BUILDMONITOR
    if buildmonitor_enabled:
        if data.get('manifestdata'):
            bm_stage = 'Update_Manifest'
            bm_data = {"bm_stage" : bm_stage,
                       "bm_start_datetime" : str(bm_start_datetime),
                       "bm_snapshot_name" : data.get('build_id'),
                       "bm_manifestdata" : data.get('manifestdata'),
                      }
            trigger_next("BUILD-MONITOR-Update_Manifest", bm_data, show=False, compress=True)
            data.pop('manifestdata')

    parm_backend = {}
    for bknd in list(reversed(range(1,99))):
        if os.getenv('BACKEND_%02d_REGEX' % bknd) and \
            re.search(r'%s' % os.getenv('BACKEND_%02d_REGEX' % bknd), data['project']) is not None:
            parm_backend['BACKEND_SELECTION'] = 'BACKEND_%02d' % bknd
            break
    trigger_next("post-snapshot", data, extra_params=parm_backend)

    # TRIGGER NEXT RSYNC-DOWNLOAD (MIRROR)
    if os.getenv("RSYNC_DOWNLOAD_ENABLED", "0") != "0":
        trigger_next('RSYNC_DOWNLOAD', data)

    # Update NUGET pacakges to server
    if os.getenv("NUGET_UPDATE_ENABLE","0") == "1":
        trigger_next("update-nuget", data)

     # Trigger REF_CREATE_PRJ_OBS to server
    if os.getenv("REF_CREATE_PRJ_OBS_ENABLE","0") == "1":
        trigger_next("REF_CREATE_PRJ_OBS", data)

    trigger_next("TEST-TRIGGER-INFO-UPDATE", data)

    if buildmonitor_enabled:

        base_build_ids = []
        bm_base_build_id = ''
        try:
            if not base_path.endswith('/'): base_path = base_path + '/'
            if not base_url.endswith('/'): base_url = base_url + '/'
            for repo in trigger_data.keys():
                for index, data in enumerate(trigger_data[repo]):
                    base_config = data.get('base_config', None)
                    if not base_config or base_config == '' or len(base_config) == 0 or '/repos/' not in base_config:
                        continue
                    base_root = base_config.split('/repos/')[0]
                    check_path = base_root.replace(base_url, base_path)
                    base_build_id = get_build_id_from_build_xml(check_path)
                    base_build_ids.append(base_build_id)
            bm_base_build_id = sorted(((base_build_ids.count(e), e) for e in set(base_build_ids)), reverse=True)[0][1]
        except Exception as err:
            print repr(err)

        bm_end_datetime = datetime.datetime.now()
        bm_snapshot_url = os.path.join(base_url, repo_data['repo_path'])
        bm_stage = 'Post_Snap_End'
        bm_data = {"bm_stage" : bm_stage,
                   "bm_start_datetime" : str(bm_start_datetime),
                   "bm_end_datetime" : str(bm_end_datetime),
                   "bm_snapshot_url" : bm_snapshot_url,
                   "bm_snapshot_name" : repo_data['build_id'],
                   "bm_duplicated" : repo_data['duplicated'],
                   "bm_buildfailreason": BuildFailReason,
                   "bm_base_build_id": bm_base_build_id
                  }
        trigger_next("BUILD-MONITOR-4-%s" % bm_stage, bm_data)

        # Skip [BUILD-MONITOR_Post_Image] if Base project
        if 'base' in project.lower():
            print '[%s] This is [Base] project!! skip Post_Image \n' % (__file__)
        else:
            # To check the completion of image-creation stage at Post-release
            #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" : repo_data['build_id']
                      }
            trigger_next("BUILD-MONITOR_Post_Image", bm_data)

    rootstrap_data = {"build_id": repo_data['build_id'],
                      "project": project,
                      }
    trigger_next("create-sdkrootstrap", rootstrap_data)

if __name__ == '__main__':
    try:
        #set num
        if len(sys.argv) > 1:
	    sys.exit(main(sys.argv[1]))
        else:
            sys.exit(main(sys.argv))
    except LocalError, error:
        print error
        sys.exit(1)

