#!/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 job require the Parameterized Build plugin, it's triggered
by http request get method to the job url, for example
http://my.host.com/job/JOB_NAME/buildWithParameters with data
"""

import sys
import os

from common.buildtrigger import trigger_next, trigger_info
from common.buildservice import BuildService
from common.backenddb import BackendDB
from common.snapshot import snapshot_project_enabled
from common.prerelease import is_prerelease_project, get_info_from_prerelease_name
from common.trbs import is_trbs_project
from common import buildmonitor_db

def isReadyForPrerelease(build, project):
    """
    isReadyForPrerelease
    """
    return True

def isReadyForTrbs(build, project):
    """
    isReadyForTrbs
    """
    return True

def isBaseCheckPrelease(project):
    """
    isBaseCheckerPrerelease
    """
    if ':basechecker:' in project:
        return True
    return False

def isReadyForCreateSnapshot(build, backenddb, project):

    # whether project is not enabled
    if not snapshot_project_enabled(backenddb, project):
        print "Skipping creating snapshot, project isn't found in repo.yaml"
        return False

    return True

def make_prefix_trigger_file(target_project):
    iso_list = os.getenv('ISOLATE_SNAPSHOT', None)
    if iso_list is None:
        return ''
    for x in iso_list.split(','):
        _prj, _prefix = x.split('=')
        if _prj == target_project:
            return _prefix.upper()
    return ''

def is_build_cycle_check_enabled(project_name):
    ret_data = 0
    try:
        buildmonitor_db.connect_db()
        query = 'SELECT build_cycle_check FROM main_project ' \
                'WHERE name=%s ;'
        ret_data = buildmonitor_db.get_value_from_query_data(query, (project_name,))
    except Exception as err:
        print repr(err)

    buildmonitor_db.disconnect_db()
    return int(ret_data)

def find_node_name(name, request_file):
    node_postfix = '%08d' % (abs(hash(name)) % (10 ** 8))
    node_name = 'download-%s' % node_postfix
    with open('NODE_TO_CREATE.env', 'w') as wf:
        wf.write('PROJECT_NAME=%s\nREQUEST_FILE=%s' % (name, request_file))
    print 'find_node_name: %s, %s' % (name, request_file)
    return 'snapshot_%s' % name

def is_devel_project(project):

    if os.getenv('OBS_DISPATCHER_DEVEL_PREFIX', None):
        for d in os.getenv('OBS_DISPATCHER_DEVEL_PREFIX').split(','):
            if project.startswith(d):
                print 'is_devel_project: True'
                return True
    print 'is_devel_project: False'
    return False

def main(obs_event_fields):
    """The main body"""

    project =  obs_event_fields.get('project') or obs_event_fields.get('sourceproject', '')
    event_type = os.getenv('event_type') 
    if(event_type == 'OBS_REPO_PUBLISHED'):
        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)
        # Init backend database
        redis_host = os.getenv("REDIS_HOST")
        redis_port = int(os.getenv("REDIS_PORT"))
        backenddb = BackendDB(redis_host, redis_port)
        if(is_prerelease_project(project)):
           if(isBaseCheckPrelease(project)):
              info = build.get_info(project)
              if info.get('build_step') == "profile_check":
                  print 'All the repositories are published for project %s.' \
                        'Triggering the prerelease.' % (project)
                  trigger_next('#PRERELEASE#%s#%s' % (project, event_type), obs_event_fields)
              elif info.get('build_step') == "base_check":
                  trigger_next('#BASE-CHECK#%s#%s' % (project, event_type), obs_event_fields)
           elif(isReadyForPrerelease(build, project)):
                print 'All the repositories are published for project %s.' \
                      'Triggering the prerelease.' % (project)
                target_project_name = get_info_from_prerelease_name(project)[0]
                obs_event_fields['build_cycle_check'] = is_build_cycle_check_enabled(target_project_name)
                if os.getenv("OBS_DISPATCHER_LOAD_BALANCING_ENABLED", "0") == "1":
                    request_file = '#LOAD_BALANCE#PRERELEASE#%s#%s' % (project, event_type)
                    print request_file
                    selected_node_name = find_node_name(target_project_name, request_file)
                    trigger_next(request_file, obs_event_fields)
                else:
                    trigger_next('%s#PRERELEASE#%s#%s' \
                                 % (make_prefix_trigger_file(target_project_name), project, event_type), \
                                 obs_event_fields)
        elif(is_trbs_project(project)):
            if(isReadyForTrbs(build, project)):
                print 'All the repositories are published for project %s.' \
                      'Triggering the trbs.' % (project)
                trigger_next('#TRBS#%s#%s' %(project,event_type),obs_event_fields)
        else:
            if(isReadyForCreateSnapshot(build, backenddb, project)):
                print 'All the repositories are published for project %s.' \
                      'Triggering the creating snapshot job..'%(project)
                obs_event_fields['build_cycle_check'] = is_build_cycle_check_enabled(project)
                if os.getenv("OBS_DISPATCHER_LOAD_BALANCING_ENABLED", "0") == "1" and not is_devel_project(project):
                    request_file = '#LOAD_BALANCE#SNAP#%s#%s' % (project, event_type)
                    selected_node_name = find_node_name(project, request_file)
                    trigger_next(request_file, obs_event_fields)
                else:
                    trigger_next('%s#SNAP#%s#%s' \
                                 % (make_prefix_trigger_file(project), project, event_type), \
                                 obs_event_fields)
    else:
        trigger_next('#%s#%s' %(project,obs_event_fields['event_type']),
                     obs_event_fields)

if __name__ == '__main__':
    # Jenkins task dispatcher, receive events from OBS jenkins notify plugin
    # and create files to trigger downstream jobs
    if len(sys.argv) != 1:
        raise SystemExit('This job do NOT support to carry parameters')

    sys.exit(main(trigger_info(os.getenv('para'))))

