#!/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 job is triggered by Gerrit RefUpdate event.
"""

import os
import sys
import json
import base64
import re
import ast
import shutil
import xml.etree.cElementTree as ElementTree
from xml.sax.saxutils import escape
from time import sleep
import datetime
import requests

from osc import core
from gitbuildsys.errors import ObsError

from common import utils
from common.mapping import git_obs_map, git_virtual_branch_map, get_ref_map
from common.git import Git, clone_gitproject
from common.upload_service import upload_obs_service, UploadError
from common.gerrit import is_ref_deleted
from common.buildservice import BuildService
from common.buildtrigger import trigger_info, trigger_next, get_jenkins_instance
from common.backenddb import BackendDB
from common.prerelease import get_prerelease_project_name, prerelease_enabled, get_info_from_prerelease_name, is_devbase_project
from common.iris_rest_client import IrisRestClient
from common.send_mail import prepare_mail
from common.gerrit import Gerrit, get_gerrit_event, GerritError, is_ref_deleted
from gbp.rpm import SpecFile
from gbp.git.repository import GitRepositoryError
from gbp.errors import GbpError

from common.workflow import create_project, find_submit_tag, check_tag_format, find_specfile, parse_specfile, get_sr_process_status

from common.buildmonitor_extention import BuildMonitorExtention

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

MODE_NORMAL = 'NORMAL'
MODE_SRSYNC = 'SR-SYNC'

TITLE_FAILED = '[Submit Request Failed]: tag: %s in %s'

TITLE_SUCCESS = '[Submit Request Success]: tag: %s in %s'

PRERELEASE_EMAIL_BODY = 'A SR (Submit Request) has been triggered to submit ' \
             'the commit to OBS project.\n' \
             'Please check the following details.\n\n' \
             'Git branch : %s\n' \
             'Git commit : %s\n\n' \
             'Git path : %s\n' \
             'Git tag : %s\n' \
             'Submitter : %s\n'

EMAIL_FOOTER = '\n\n--------------------------------------------------------\n'\
               'Automatically generated by backend service.\n'\
               'Please DO NOT Reply!'

def send_mail(title, msg, receiver):
    """ post message back to gerrit and send mail to tag owner """
    print 'msg %s' % msg
    if 'author' in receiver and 'email' in receiver:
        msg = 'Hi, %s,\n\n' % receiver['author'] + msg + EMAIL_FOOTER
        prepare_mail("%s.env" % os.getenv('BUILD_TAG'), title, msg,
                     os.getenv('NOREPLY_EMAIL_SENDER'), receiver['email'])

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

def get_branch_name(tag):
    """Get branch name by parsing info
       from submit tag name.
    """
    branch = None
    if tag.startswith('submit/'):
        pos = tag.rfind('/', len('submit/'))
        if pos != -1:
            branch = tag[len('submit/'):pos]
            if branch == 'trunk':
                branch = 'master'
    return branch

def send_mail_sr_message(info):
    """ send mail about buildstatus """

    #make a message
    title = TITLE_SUCCESS % ( info['submitted'].get('tag'), info['submitted'].get('gitpath'))
    email_body = PRERELEASE_EMAIL_BODY % (info['submitted'].get('branch'), \
                                          info['submitted'].get('commit_id'), \
                                          info['submitted'].get('gitpath'), \
                                          info['submitted'].get('tag'), \
                                          info['submitted'].get('submitter')
                                         )
    #add products project
    email_body += 'obs_prj : %s \n' %(info['pre_created'])

    msg = 'Hello \n\n' + email_body + EMAIL_FOOTER
    print title
    print msg
    submitter = info['submitted'].get('submitter')
    if info['submitted'].get('submitter_email'):
        submitter += ' <%s>' % info['submitted'].get('submitter_email')
    if submitter:
        prepare_mail("%s.env" % os.getenv('BUILD_TAG'), title, msg,
                     os.getenv('NOREPLY_EMAIL_SENDER'), submitter)

queued_requests = {} # key would be project name (home:prerelease:...)
def enqueue_request(event, url, git_tag,
                    build, obs_target_prj, ref_obs_target_prj, project, submitter, package, build_flag=True):
    # Check group submits...
    enqueue_item = {'url': url, \
                    'gerrit_project': event.get('project'), \
                    'git_tag': git_tag, \
                    'gerrit_newrev': event.get('newrev'), \
                    'obs_target_prj': obs_target_prj, \
                    'ref_obs_target_prj': ref_obs_target_prj, \
                    'project': project, \
                    'submitter': submitter, \
                    'package': package, \
                    'build_flag': build_flag, \
                    'github_type': event.get('github_type'), \
                    'github_fetch_url': event.get('github_fetch_url'), \
                    'github_full_name': event.get('github_full_name')
                   }
    if project in queued_requests:
        queued_requests[project].append(enqueue_item)
    else:
        queued_requests[project] = [enqueue_item]
    print 'QUEUED... %s\n' % enqueue_item

def process_requests(build, request_q):

    retry_count = 3
    for x in request_q['requests']:
        args = x[x.keys()[0]]
        # Re-arrange SR-SYNC
        if request_q['reason'] == MODE_SRSYNC:
            for a in args:
                a['url'] = request_q['url']
                a['obs_target_prj'] = request_q['obs_target_prj']
        while retry_count >= 0:
            try:
                create_project(build, x.keys()[0], args, mode=request_q['reason'])
                break
            except Exception as err:
                print 'create_project error: %s' % repr(err)
                retry_count -= 1
    if retry_count < 0:
        return -1
    return 0

def entry_github(option):
    """ Entry github """
    print '\n** Forward %s to group routine' % os.getenv('GERRIT_REFNAME')

    payload = json.loads(os.getenv('payload'))
    payload_repository = payload.get('repository')
    payload_sender = payload.get('sender')

    if payload is None or \
        (payload.get('deleted') is not None and payload.get('deleted') == 'true'):
        print 'skip this job \n palyload = %s ' %(payload)
        return

    git_tag = payload.get('ref')
    if not git_tag:
        print 'skip this job \n No git_tag'
        return
    # check whether tag name is start with 'submit/'
    if not git_tag.startswith('submit/'):
        print '\nREFNAME "%s" isn\'t start with submit, exit now'\
              % git_tag
        return

    git_branch = get_branch_name(git_tag)

    git_cache = os.getenv("GIT_CACHE_DIR")
    git_full_name = payload_repository.get('full_name')
    prjdir = os.path.join(git_cache, git_full_name)
    giturl, gitproject = payload_repository.get('ssh_url').split('/')
    gitproject = gitproject.split('.git')[0]
    gitorg = giturl.split(':')[1]
    git_cache_dir = os.path.join(git_cache, gitorg)

    if not clone_gitproject(gitproject, prjdir, giturl=giturl, git_cache_dir=git_cache_dir):
        print >> sys.stderr, 'Error cloning %s' % payload['project']
        return 1
    mygit = Git(prjdir)
    mygit.checkout(git_tag)
    #TODO: Find commit id
    commit_id = mygit.rev_parse('HEAD')
    print 'commit_id: %s' % commit_id

    result_str, cd_err, cd_ret = mygit._git_inout('for-each-ref', \
                                 ['--format=%(tagger)', 'refs/tags/%s' %(git_tag)])
    lparen = result_str.find('<')
    rparen = result_str.find('>')
    account_name = result_str[0:lparen]
    account_email = result_str[lparen+1:rparen]
    info_data = ""
    info_data += '%s=%s\n' % ('GERRIT_EVENT_TYPE', 'ref-updated')
    info_data += '%s=%s\n' % ('GERRIT_EVENT_HASH', payload_repository.get('id'))
    info_data += '%s=%s\n' % ('GERRIT_REFNAME', 'refs/tags/' + payload.get('ref'))
    info_data += '%s=%s\n' % ('GERRIT_PROJECT', gitproject)
    info_data += '%s=%s\n' % ('GERRIT_OLDREV', '0000000000000000000000000000000000000000')
    info_data += '%s=%s\n' % ('GERRIT_NEWREV', commit_id)
    info_data += '%s=%s\n' % ('GERRIT_EVENT_ACCOUNT', '%s <%s>' %(account_name, account_email))
    info_data += '%s=%s\n' % ('GERRIT_EVENT_ACCOUNT_NAME', account_name)
    info_data += '%s=%s\n' % ('GERRIT_EVENT_ACCOUNT_EMAIL', account_email)
    info_data += '%s=%s\n' % ('GERRIT_GITHUB_FETCH_URL', giturl )
    info_data += '%s=%s\n' % ('GERRIT_GITHUB_FULL_NAME', git_full_name )
    info_data += '%s=%s\n' % ('GERRIT_GITHUB_TYPE', True )

    with open('PRE-RELEASE-SUBMIT_%d.env' % int(os.getenv('BUILD_NUMBER')), 'w') as info_f:
        info_f.write(info_data)
        print info_data
    return

def entry(option):
    print option
    if len(option) > 2 and option[2] == 'bypass':

        # Check BUILD-MONITOR DB
        my_tag = os.getenv('GERRIT_REFNAME').replace('refs/tags/', '')
        reas = get_sr_process_status(my_tag)
        print reas
        if reas is not None:
            print 'Your SR process already completed'
            send_mail(TITLE_FAILED % (my_tag, os.getenv('GERRIT_PROJECT')), \
                      reas, {'author': os.getenv('GERRIT_EVENT_ACCOUNT_NAME'), \
                             'email':os.getenv('GERRIT_EVENT_ACCOUNT_EMAIL')})
            return

        print '\n** Forward %s to group routine' % os.getenv('GERRIT_REFNAME')
        with open('PRE-RELEASE-SUBMIT-GROUP_%d.env' % int(os.getenv('BUILD_NUMBER')), 'w') as info_f:
            for x in ['EVENT_TYPE', 'EVENT_HASH', 'REFNAME', 'PROJECT', 'OLDREV', 'NEWREV', \
                      'EVENT_ACCOUNT', 'EVENT_ACCOUNT_NAME', 'EVENT_ACCOUNT_EMAIL']:
                info_f.write('%s=%s\n' % ('GERRIT_' + x, os.getenv('GERRIT_' + x)))
                print '    %s=%s' % (x, os.getenv('GERRIT_' + x))
            #github type
            if os.getenv('GERRIT_GITHUB_TYPE',None):
                info_f.write('%s=%s\n' % ('GERRIT_GITHUB_TYPE', os.getenv('GERRIT_GITHUB_TYPE')))
            if os.getenv('GERRIT_GITHUB_FETCH_URL',None):
                info_f.write('%s=%s\n' % ('GERRIT_GITHUB_FETCH_URL', os.getenv('GERRIT_GITHUB_FETCH_URL')))
            if os.getenv('GERRIT_GITHUB_FULL_NAME',None):
                info_f.write('%s=%s\n' % ('GERRIT_GITHUB_FULL_NAME', os.getenv('GERRIT_GITHUB_FULL_NAME')))
        return
    elif len(option) > 2 and option[2] == 'github':
        entry_github(option)
        return

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

    build = BuildService(obs_api, obs_user, obs_passwd)

    # Split obs creation job
    if len(option) > 2 and option[2] == 'request':
        content = trigger_info(os.getenv('TRIGGER_INFO'))
        return process_requests(build, content)

    # First store current build and all the rest queued builds
    build_queue = []
    job = os.getenv('JOB_NAME')
    cred = {'url': os.getenv('JENKINS_URL_INTERNAL'), \
            'username': os.getenv('JENKINS_USER'), \
            'password': os.getenv('JENKINS_PW')}
    for jenkins_conn_retry in (1, 2, 3):
        try:
            jenkinsinst = get_jenkins_instance(job, cred)
            curr_build = jenkinsinst.get_job(job).get_build(int(os.getenv('BUILD_NUMBER')))
            break
        except Exception as err:
            print str(err)
            curr_build = None
            sleep(1)
            continue

    curr_data = {}
    up_id = 0
    if curr_build:
        up_id = curr_build.get_upstream_build_number()
        if up_id is None:
            up_id = 0
        for k in curr_build.get_actions()['parameters']:
            curr_data[k['name']] = k['value']
        build_queue.append({'%d-%d' % (up_id, curr_build._data['queueId']): curr_data})
    else:
        #FIXME: python-jenkinsapi fail to retrive internal url. Use api/python call instead.
        path = '%s/job/%s/%s/api/python' % (cred['url'], os.getenv('JOB_NAME'), os.getenv('BUILD_NUMBER'))
        path = path.replace('://', '://%s:%s@' % (cred['username'], cred['password']))
        resp = requests.get(path)
        ret_obj = ast.literal_eval(resp.text)
        for a in ret_obj['actions']:
            if 'causes' in a:
                if up_id == 0 and 'upstreamBuild' in a['causes'][0]:
                    up_id = int(a['causes'][0]['upstreamBuild'])
            if 'parameters' in a:
                for p in a['parameters']:
                    curr_data[p['name']] = p['value']
        build_queue.append({'%d-%d' % (up_id, int(ret_obj['queueId'])): curr_data})

    # Keep original process
    if up_id != 0:
        jq = jenkinsinst.get_queue()
        for pending_build in jq.get_queue_items_for_job(os.getenv('JOB_NAME')):
            for action in pending_build._data.get('actions', []):
                if type(action) is dict and 'causes' in action:
                    up_id = [x.get('upstreamBuild', None) for x in action['causes']][0]
                    if up_id is None: up_id = 0
                    break
            build_queue.append({'%d-%d' % (up_id, pending_build.queue_id): pending_build.get_parameters()})
            print '\n    %s DELETED: %s' % (pending_build.queue_id, pending_build.get_parameters())
            jq.delete_item_by_id(pending_build.queue_id)

    build_queue = sorted(build_queue)
    print '\nBelow will be proceeded: "%s"' % [int(k.keys()[0].split('-')[0]) for k in build_queue]
    for k in build_queue:
        item = k[k.keys()[0]]
        print '%s : %s(%s)' % (k.keys()[0], \
                               item['GERRIT_PROJECT'], \
                               item['GERRIT_NEWREV'])

    #event = get_gerrit_event("PUBLIC_")
    event = get_gerrit_event()
    sr_count = 1
    for k in build_queue:
        item = k[k.keys()[0]]
        # Just forward it to main routine. (Merging group submits need target project name)
        print item['GERRIT_PROJECT'], item['GERRIT_NEWREV']
        event.update({'project': item['GERRIT_PROJECT'], \
                      'refname': item['GERRIT_REFNAME'], \
                      'oldrev': item['GERRIT_OLDREV'], \
                      'newrev': item['GERRIT_NEWREV'], \
                      'event_account': item['GERRIT_EVENT_ACCOUNT'], \
                      'event_account_name': item['GERRIT_EVENT_ACCOUNT_NAME'], \
                      'event_account_email' : item['GERRIT_EVENT_ACCOUNT_EMAIL'], \
                      'event_type': item['GERRIT_EVENT_TYPE'], \
                      'event_hash': item['GERRIT_EVENT_HASH'], \
                      'github_type': item['GERRIT_GITHUB_TYPE'], \
                      'github_fetch_url': item['GERRIT_GITHUB_FETCH_URL'], \
                      'github_full_name': item['GERRIT_GITHUB_FULL_NAME']}
                      )
        print "option?%s" + option[1]
        main(option[1], build, event, sr_count)
        sr_count += 1

    for x in queued_requests:
        print '\n[%s]:\n  %s' % (x, queued_requests[x])

    # Split obs creation job
    queued_requests_list = []
    for x in queued_requests:
        queued_requests_list.append({x: queued_requests[x]})
    trigger_next('PRE_RELEASE_REQUEST', {'requests': queued_requests_list, 'reason': 'NORMAL'}, compress=True)

    return 0
 
def main(build_type, build, event, sr_count):
    """
    Script entry point.
    Parameters:
       build_type - type of the build (prerelease, snapshot)

    """

    print '---[JOB STARTED]-------------------------'
    buildmonitor_enabled = os.getenv("BUILDMONITOR_ENABLED", "0") != "0"
    print 'buildmonitor_enabled(%s)\n' % (buildmonitor_enabled)
    if buildmonitor_enabled:
        bm_start_datetime = datetime.datetime.now()

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

    # Triggered by Gerrit - use GERRIT_REFNAME to get tag
    git_tag = event['refname'].split("refs/tags/")[1]
    git_branch = get_branch_name(git_tag)

    # prepare separate temp directory for each build
    git_cache = os.getenv("GIT_CACHE_DIR")

    # Enable Github Connection
    if event.get('github_type'):
        giturl = event.get('github_fetch_url')
        prjdir = os.path.join(git_cache, event.get('github_full_name'))
        gitorg = giturl.split(':')[1]
        git_cache_dir = os.path.join(git_cache, gitorg)
    else: # GERRIT
        prjdir = os.path.join(git_cache, event['project'])
        giturl = None # os.getenv('GERRIT_FETCH_URL')
        git_cache_dir = None

    # clone gerrit project to local dir
    if not clone_gitproject(event['project'], prjdir, giturl=giturl, git_cache_dir=git_cache_dir):
        print >> sys.stderr, 'Error cloning %s' % event['project']
        return 1
    mygit = Git(prjdir)

    tag = find_submit_tag(event, mygit)
    if not tag:
        print '\nThis commit don\'t contain submit/*/* tag, exit now'
        return 0

    # checkout submit tag
    try:
        mygit.checkout(tag)
    except Exception as err:
        print 'Retrying git cloning due to checkout failure. %s' % repr(err)
        shutil.rmtree(prjdir)
        if not clone_gitproject(event['project'], prjdir):
            print >> sys.stderr, 'Error cloning %s' % event['project']
            return 1
        mygit = Git(prjdir)
        mygit.checkout(tag)

    # check whether tag name is start with 'submit/'
    if not event['refname'].startswith('refs/tags/submit/'):
        print '\nREFNAME "%s" isn\'t start with refs/tags/submit, exit now'\
              % event['refname']
        return 0
    elif is_ref_deleted(event['oldrev'], event['newrev']):
        print '\nREFNAME "%s" is deleted, exit now' % event['refname']
        #receiver = { 'author' : event['event_account_name'],
        #             'email'  : event['event_account_email'] }
        #send_mail('[GBS submit guide] Deleting a SR tag is not recommended.', \
        #          '\nYou just deleted a tag %s.\n' \
        #          'From CI POV, we do not recommend you to delete a tag.\n' \
        #          'Thank you for your understanding.\n' \
        #           % (receiver.get('author'), event['refname']), receiver)
        return 0

    result_str, cd_err, cd_ret = mygit._git_inout('for-each-ref', ['--format=%(tagger)', event['refname']])
    lparen = result_str.find('<')
    rparen = result_str.find('>')
    gerrit_account_name = result_str[0:lparen]
    gerrit_account_email = result_str[lparen+1:rparen]
    gerrit_account_name = gerrit_account_name.encode('ascii', 'ignore')
    gerrit_account_email = gerrit_account_email.encode('ascii', 'ignore')

    submitter = ''
    if gerrit_account_name:
        submitter = gerrit_account_name
        if gerrit_account_email:
            submitter += ' <%s>' % gerrit_account_email

    # Enable Github Connection.
    if not event.get('github_type'):
        mygerrit = Gerrit(event['hostname'], event['username'], \
                event['sshport'], int(os.getenv('GERRIT_SILENT_MODE')))

        # check whether tag meet format
        resp = check_tag_format(mygit, mygerrit, event, tag)
        if resp is not None:
            if 'author' not in resp['tagger'] or 'email' not in resp['tagger']:
                recevier = { 'author' : event['event_account_name'],
                             'email'  : event['event_account_email'] }
                send_mail(TITLE_FAILED % (tag, event['project']), resp['message'], recevier)
            else:
                send_mail(TITLE_FAILED % (tag, event['project']), resp['message'], resp['tagger'])
            print 'The check for the tag format is error, exit now\n'
            return 0

    bm_ext = BuildMonitorExtention()

    packagingdir = utils.parse_link('%s/%s' % (prjdir, 'packaging'))
    print 'packaging dir is %s/%s' % (prjdir, packagingdir)

    tagger = mygit.get_tag(tag)

    # get project mappings from git-obs-mapping and git-ref-mapping
    if git_branch.endswith('_tpk') or git_branch.endswith('_wgt'): # ABS - mappings w/o _tpk postfix(only for profiles).
        abs_branch_postfix = git_branch[-4:]
        work_branch = git_branch
        if os.getenv('ABS_SUPPORTED_PROFILES', None):
            for sp in os.getenv('ABS_SUPPORTED_PROFILES').split(','):
                work_branch = work_branch.replace('_%s%s' % (sp.lower(), abs_branch_postfix), '')
            work_branch = work_branch.replace(abs_branch_postfix, '')
        else:
            work_branch = work_branch.replace(abs_branch_postfix, '')
        print 'work_branch:%s' % work_branch
        obs_target_prjs = git_obs_map(event['project'], work_branch)
        if os.getenv("REF_USE_FOR_PRERELEASE","0") == "1":
            obs_ref_prjs = get_ref_map(event['project'], work_branch)
    else:
        obs_target_prjs = git_obs_map(event['project'], git_branch)
        if os.getenv("REF_USE_FOR_PRERELEASE","0") == "1":
            obs_ref_prjs = get_ref_map(event['project'], git_branch)

    # Get all project lists
    all_obs_prjs = build.get_project_list()

    # prepare submit_info
    submit_info={}
    submit_info['submitted'] = {
                "branch": git_branch,
                "commit_id": event['newrev'],
                "gitpath": event['project'],
                "submitter": gerrit_account_name,
                "submitter_email": gerrit_account_email,
                "tag": git_tag,
                }
    submit_info['pre_created'] = []

    # Enable Github Connection.
    if event.get('github_type'):
        url = '%s' %( event.get('github_fetch_url'))
    else:
        url = 'ssh://%s:%s' % (os.getenv('GERRIT_HOSTNAME_EXTERNAL'),
                               os.getenv('GERRIT_SSHPORT'))
    for item in obs_target_prjs:
        enable_build = True
        obs_target_prj = item['OBS_project']
        obs_stg_prj = item['OBS_staging_project']
        obs_pkg = item['OBS_package']
        obs_use_specname = item['OBS_use_specname']

        if build_type == 'prerelease':
            if obs_stg_prj == 'abs' \
                and (git_branch.endswith('_tpk') or git_branch.endswith('_wgt')):
                    print 'Create ABS prerelease project...'
            elif git_branch.endswith('_tpk') or git_branch.endswith('_wgt'):
                print('%s belongs to ABS but %s is not!' % (git_branch, obs_stg_prj))
                continue
            elif obs_stg_prj != 'prerelease':
                print "%s is not 'prerelease' project in git-obs-mapping.xml." \
                      "It has been switched to submitobs workflow." \
                      "Skipping ..." % obs_stg_prj
                continue

        if 'config' in item and item['config'] is not None and item['config'].enable == 'false':
            print 'SR for %s is not enabled' % (obs_target_prj)
            continue
        if 'config' in item and item['config'] is not None and item['config'].build == 'no':
            print 'Set disable build for %s' % (obs_target_prj)
            enable_build = False
        if obs_use_specname == 'yes':
            # search specfile under packaging directory
            resp = find_specfile(prjdir, packagingdir, tag, event, tagger)
            if not resp['spec']:
                send_mail(TITLE_FAILED % (tag, event['project']), resp['message'], tagger)
                return 0
            # parse specfile
            resp = parse_specfile(resp['spec'], tag, event, tagger)
            if not resp['spec']:
                send_mail(TITLE_FAILED % (tag, event['project']), resp['message'], tagger)
                return 0
            package = resp['spec'].name
            print 'spec name = %s' %(resp['spec'].name)
        else:
            # get package name from xml files.
            if obs_pkg:
                package = obs_pkg
            else:
            # get package name from gerrit_project
                package = os.path.basename(event['project'])
        print 'package name = %s' %(package)

        if build_type == 'prerelease':
            if not prerelease_enabled(backenddb, obs_target_prj):
                print 'Skipping %s as prerelease is not enabled for it' % \
                       obs_target_prj
                continue
            project = get_prerelease_project_name(obs_target_prj, git_tag)

            ref_obs_target_prj = obs_target_prj
            # Set obs_target_prj to ref project if it is enabled
            if os.getenv("REF_USE_FOR_PRERELEASE","0") == "1":
                # Check if this is the group submit.
                existing_link_info = build.get_link_project_info(project)
                if existing_link_info is not None and build.exists(existing_link_info):
                    print 'Project already exist. Use previous ref project %s' % existing_link_info
                    ref_obs_target_prj = existing_link_info
                else:
                    if obs_target_prj in [ x['project'] for x in ast.literal_eval(os.getenv('REF_ACTIVE_PRJS')) ]:
                        for ref_info in obs_ref_prjs:
                            if ref_info['OBS_project'] != obs_target_prj:
                                continue
                            ret_ref = re.search(r'(%s):ref:([0-9]{8}.[0-9]+)' % obs_target_prj, \
                                                ref_info['OBS_staging_project'])
                            if not ret_ref or not ret_ref.groups() or len(ret_ref.groups()) != 2:
                                continue
                            print ' ** Set target link project to %s' % ref_info['OBS_staging_project']
                            ref_obs_target_prj = ref_info['OBS_staging_project']
                    # If ref-map does not exists, set the most recent ref project
                    associated_prjs = sorted([ p for p in all_obs_prjs if '%s:ref:' % obs_target_prj in p ])
                    if not associated_prjs or len(associated_prjs) < 1:
                        print 'No ref project for %s' % obs_target_prj
                        ref_obs_target_prj = obs_target_prj
                    elif ref_obs_target_prj not in associated_prjs:
                        print 'No ref map exist. Set it recent ref project %s' % associated_prjs[-1]
                        ref_obs_target_prj = associated_prjs[-1]
            sys.stdout.flush()

            if is_ref_deleted(event['oldrev'], event['newrev']):
                build.cleanup(project, "Cleaned by job_submit")
            else:
                submitter = ''
                if gerrit_account_name:
                    submitter = gerrit_account_name
                    if gerrit_account_email:
                        submitter += ' <%s>' % gerrit_account_email

                enqueue_request( event, url, git_tag,
                                build, obs_target_prj, ref_obs_target_prj, project, submitter, package, build_flag=enable_build)
                if True:
                        # prepare submit_info
                        if project:
                            products = submit_info['pre_created'] or []
                            if not obs_target_prj in products:
                                submit_info['pre_created'].append(project)
                            else:
                                submit_info['pre_created'] = products
        elif build_type == 'snapshot':
            if not is_ref_deleted(event['oldrev'], event['newrev']):
                if build.exists(obs_target_prj):
                    # Upload _service to target project
                    try:
                        upload_obs_service(url, event['project'], git_tag, \
                                event['newrev'], obs_target_prj, build, package)
                    except UploadError, err:
                        raise LocalError(err)
                else:
                    print "Warning: target project %s doesn't exist, " \
                          "skipping" % obs_target_prj
    # send mail
    if submit_info['pre_created']:
        send_mail_sr_message(submit_info)

        if buildmonitor_enabled:
            bm_end_datetime = datetime.datetime.now()
            commit_date, cd_err, cd_ret = mygit._git_inout('show', ['-s', '--format=%ci'])
            commit_msg, cm_err, cm_ret = mygit._git_inout('show', ['-s', '--format=%s'])
            submit_date, sd_err, sd_ret = mygit._git_inout('for-each-ref', \
                        ['--count=1', '--sort=-taggerdate', '--format=%(taggerdate:iso)', 'refs/tags/%s' % git_tag])
            submit_msg, sm_err, sm_ret = mygit._git_inout('for-each-ref', \
                        ['--count=1', '--sort=-taggerdate', '--format=%(subject)', 'refs/tags/%s' % git_tag])
            submitter, st_err, st_ret = mygit._git_inout('for-each-ref', \
                        ['--count=1', '--sort=-taggerdate', '--format=%(taggeremail)', 'refs/tags/%s' % git_tag])
            #print '[%s] %s%s' % (__file__, commit_date, commit_msg)
            #print '[%s] %s%s%s' % (__file__, submit_date, submit_msg, submitter)

            ### sr_status -> sr_commit -> sr_stage & sr_status_detail
            #buildmonitor.sr_submit_for_sr_status(git_tag)
            #buildmonitor.sr_submit_for_sr_commit(mygit, git_tag, gerrit_project,
            #                                     gerrit_newrev, gerrit_account_name)
            #buildmonitor.package_build_for_sr_detail_sr_stage(git_tag, bm_start_datetime,
            #                                                  bm_end_datetime,
            #                                                  submit_info['pre_created'])

            # Enable Github Connection.
            if event.get('github_type'):
                git_project = "%s/%s" %(event.get('github_fetch_url'), event.get('project'))
            else:
                git_project = event.get('project')

            status = ""
            if not is_devbase_project(project):
                contains, renamed = bm_ext.is_contain_git_in_project(obs_target_prj, git_project, package)
                if contains == -1:
                    # different git path
                    status = "N"
                elif contains == -2:
                    # different package name
                    status = "R,(%s)" %(renamed)
                else:
                    status = ""

            bm_stage = 'Submit'
            bm_data = {"bm_stage" : bm_stage,
                       "commit_date" : commit_date,
                       "commit_msg" : commit_msg,
                       "submit_date" : submit_date,
                       "submit_msg" : submit_msg,
                       "submitter" : submitter,
                       "status" : status,
                       "git_tag" : git_tag,
                       "obs_package_name" : package,
                       "gerrit_project" : git_project,
                       "gerrit_newrev" : event['newrev'],
                       "gerrit_account_name" : gerrit_account_name,
                       "bm_start_datetime": str(bm_start_datetime),
                       "bm_end_datetime": str(bm_end_datetime),
                       "bm_src_project_lst": submit_info['pre_created']
                        }
            ### sr_status -> sr_commit -> sr_stage & sr_status_detail
            trigger_next("BUILD-MONITOR_%d" % sr_count, bm_data)

if __name__ == '__main__':
    #try:
        sys.exit(entry(sys.argv))
    #except Exception as err:
    #    print err
    #    sys.exit(1)

