#!/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
from datetime import datetime


def change_name_snapshot_to_ref_project(target_project, snapshot):
    snapshot_version_num = snapshot.split('_')[1]
    project_name = "%s:ref:%s" % (target_project, snapshot_version_num)

    return project_name


def change_format_trigger_info(info):

    ref_base_prj = change_name_snapshot_to_ref_project(
        info.get('base_target_prj'), info.get('ref_base_prj'))
    latest_base_prj = change_name_snapshot_to_ref_project(
        info.get('base_target_prj'), info.get('latest_base_prj'))
    ref_profile_prj = change_name_snapshot_to_ref_project(
        info.get('obs_target_prj'), info.get('ref_profile_prj'))

    data = dict(info)    
    data.update({"ref_base_prj": ref_base_prj,"latest_base_prj": latest_base_prj,"ref_profile_prj": ref_profile_prj})

    return data


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

    basecheck_info = change_format_trigger_info(obs_event_fields)
    trigger_next("BASECHECK", basecheck_info)


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('TRIGGER_INFO'))))

