#!/usr/bin/env python

import sys
import os
import tempfile
import atexit
import shutil
import urllib2
import subprocess
import gzip
import re
import glob
from datetime import datetime
from common.git import Git, clone_gitproject
from common.gerrit import Gerrit, get_gerrit_event, GerritError, is_ref_deleted
from common.buildservice import BuildService
from common.utils import sync
from common.gbsutils import GBSBuild, gbs_update_dashboard
from common.buildtrigger import trigger_info,trigger_next

# prepare related global variables
workspace = os.getenv('WORKSPACE')
basic_url= os.getenv('URL_PUBLIC_REPO_BASE') + '/snapshots/tizen/'
#gbsbuild_workspace = '/data/gbsbuild-ROOT/'
gbsbuild_workspace = '/srv/data/gbsbuild-ROOT/'
BUILD_ROOT = gbsbuild_workspace + '/GBS-ROOT/'
src_root = gbsbuild_workspace + '/SRC-ROOT/'
LIVE_ROOT = gbsbuild_workspace + '/live/'

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

def main():
    """script entry point"""

    print '---[JOB STARTED]----------------------------------------'

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

    obs_prj = os.getenv('PROJECT')
    snapshot_num = os.getenv('SNAPSHOT')
    trigger_category = os.getenv('TRIGGER_CATEGORY')
    new_pkg_list = os.getenv('NEW_PKG_LIST')
    rm_pkg_list = os.getenv('RM_PKG_LIST')
    rm_from_img_list = os.getenv('RM_FROM_IMG')
    add_to_img_list = os.getenv('ADD_TO_IMG')

    # If there is no direct input from input parameters, let build parameters come from trigger_info
    if not obs_prj:
        obs_prj = contents.get("main_project")
    if not snapshot_num:
        snapshot_num = contents.get("source_snapshot").split("_")[1]
    if not trigger_category:
        trigger_category = contents.get("gbs_type")
    if not new_pkg_list:
        new_pkg_list = ''
        if contents.get("packages"):
            for pkg in contents.get("packages"):
                if pkg.values()[0]['build'] == 'include':
                    new_pkg_list += (pkg.keys()[0]+' '+pkg.values()[0]['commit']+' ')
            new_pkg_list=new_pkg_list[:-1]
    if not rm_pkg_list:
        rm_pkg_list = ''
        if contents.get("packages"):
            for pkg in contents.get("packages"):
                if pkg.values()[0]['build'] != 'include':
                    rm_pkg_list += (pkg.keys()[0]+' ')
            rm_pkg_list=rm_pkg_list[:-1]
    if not rm_from_img_list:
        rm_from_img_list = ''
        if contents.get("packages"):
            for pkg in contents.get("packages"):
                if pkg.values()[0]['image'] != 'include':
                    rm_from_img_list += (pkg.keys()[0]+' ')
            rm_from_img_list=rm_from_img_list[:-1]
    if not add_to_img_list:
        add_to_img_list = []
        if contents.get("packages"):
            for pkg in contents.get("packages"):
                if pkg.values()[0]['image'] == 'include':
                    add_to_img_list.append ({'git_name':pkg.keys()[0]})
                    add_to_img_list[-1]['rpm_name'] = pkg.values()[0]['rpm_name']
                    add_to_img_list[-1]['pattern_name'] = pkg.values()[0]['pattern_name']

    #tempary_test_code
    #temprary add_to_img_list
#    add_to_img_list = [{'git_name':'platform/core/api/haptic','rpm_name':'capi-system-haptic','pattern_name':'mobile-middleware'}, {'git_name':'platform/core/api/usb-accessory','rpm_name':'capi-system-usb-accessory','pattern_name':'mobile-middleware'}]

    gbsbuild_tag = contents.get("tag")

    print "Build Parameters:\nobs_prj: %s\nsnapshot_num: %s\ntrigger_category: %s\nnew_pkg_list: %s\nrm_pkg_list: %s\nrm_from_img_list: %s\ngbsbuild_tag:%s\n" %(obs_prj,snapshot_num,trigger_category,new_pkg_list,rm_pkg_list,rm_from_img_list,gbsbuild_tag)

    global buildmonitor_enabled
    buildmonitor_enabled = os.getenv("BUILDMONITOR_ENABLED", "0") != "0"
    print 'buildmonitor_enabled(%s)\n' % (buildmonitor_enabled)

    print 'gbs fullbuild start which links to obs project: %s' %obs_prj

    gbsbuild = GBSBuild(gbsbuild_tag, obs_prj, basic_url, snapshot_num, trigger_category, new_pkg_list, rm_pkg_list, rm_from_img_list, add_to_img_list, gbsbuild_workspace)
    gbsbuild_dic = gbsbuild.convert_gbsbuild_to_dictionary()
    print "gbsbuild_dic : %s" %gbsbuild_dic

    if buildmonitor_enabled:
        build_pkg_data = gbsbuild.get_build_pkg_data()
        bm_stage = 'GBSDBBuild_Start'
        bm_data = {"bm_stage" : bm_stage,
                   "gbsbuild_tag" : gbsbuild_tag,
                   "trigger_category" : trigger_category,
                   "obs_prj" : obs_prj,
                  }
        trigger_next("BUILD-MONITOR-%s" % bm_stage, bm_data)

    repo_arch_list = []
    for repo in gbsbuild_dic['repository']:
#tempary_test_code    for repo in ['standard']:
        for arch in gbsbuild_dic['arch_list'][repo]:
#tempary_test_code        for arch in ['armv7l']:
            print 'OBS Project: %s, repository: %s, architecture: %s gbs build start'\
                   %(gbsbuild_dic['obs_prj'],repo,arch)
            repo_arch_list.append({"repo":repo,"arch":arch})
            trigger_next('gbsdbbuild_one_repoarch_build_%s_%s' % (repo, arch),\
                    {'gbsbuild_dic':gbsbuild_dic,
                     'repository':repo,
                     'architecture':arch,
                     'new_pkg_list':new_pkg_list,
                     'rm_pkg_list':rm_pkg_list,
                     'rm_from_img_list':rm_from_img_list})
#tempary_test_code
#    return 0

    if buildmonitor_enabled:
        gbs_update_data = {"tag" : gbsbuild_dic['gbsbuild_tag'],
                           "mode" : "build_queued",
                           "reason" : {"repo_arch_list":repo_arch_list}}
        gbs_update_dashboard(gbs_update_data,via='direct_call')

        mode = "snapshot_queued"
        gbs_update_data = {"tag" : gbsbuild_dic['gbsbuild_tag'],
                           "mode" : mode}
        gbs_update_dashboard(gbs_update_data,via='trigger',trigger_name=mode)

    # TRIGGER NEXT GBSFULLBUILD-CREATE-SNAPSHOT
    git_ref_mapping_info = contents.get('git_ref_mapping_info',{})
    trigger_next("gbsdbbuild-create-snapshot",\
        {'gbsbuild_dic':gbsbuild_dic,
         'git_ref_mapping_info':git_ref_mapping_info
            })


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

