#!/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 script is used to update infomation about images"""

import os
import sys
import base64
import json
import ast

from common.gerrit import get_gerrit_event, GerritEnv
from common.git import Git, clone_gitproject
from common.buildtrigger import trigger_next, trigger_info, trigger_jenkins_build, remote_jenkins_build_job

GIT_FILE_NAME = 'prerelease.description'


def local_trigger_for_tester(events, gerrit_env):
    """ trigger local tester """

    print 'localtrigger_for_tester\n'

    if os.getenv('TRIGGER_INFO'):
        content = trigger_info(os.getenv('TRIGGER_INFO'))

        # Check if we've got required field in TRIGGER_INFO
        for field in ('git_tag', 'download_url', 'projects', 'obs_target_prj'):
            if field not in content:
                print 'Error: TRIGGER_INFO doesn\'t contain %s' % field
                return -1

        # trigger sync obs job
        trigger_jenkins_build(os.getenv('TEST_JOB_NAME'), \
                             {'TRIGGER_INFO': os.getenv('TRIGGER_INFO')}, \
                              cred={'url': os.getenv('TEST_JENKINS_URL'), \
                              'username': os.getenv('TEST_JENKINS_USER'), \
                              'password': os.getenv('TEST_JENKINS_PW')}, \
                              block=False
                             )
    else:

        git_prjdir = os.path.join(gerrit_env.gitcache, events['project'])

        # clone_gitproject
        if not clone_gitproject(events['project'], \
                                git_prjdir,
                                gerrit_hostname=gerrit_env.hostname, \
                                gerrit_username=gerrit_env.username, \
                                gerrit_sshport=gerrit_env.sshport):
           print >> sys.stderr, 'Error cloning %s' % events['project']
           return 1

        # get prerelease_description_dict data
        mygit = Git(git_prjdir)
        commit_id = os.getenv("GERRIT_NEWREV")
        arg = commit_id + ':' + GIT_FILE_NAME

        prerelease_description_str = mygit.show(arg)
        prerelease_description_dict = json.loads(prerelease_description_str)
        print json.dumps(prerelease_description_dict, indent=4)

        # set the jenkins info
        refname = os.getenv("GERRIT_REFNAME")
        print 'refname : %s\n' % refname
        if True:
            url_lst = os.getenv("TEST_SR_GATE_JENKINS_URL", "").split(',')
            user_lst = os.getenv("TEST_SR_GATE_JENKINS_USER", "").split(',')
            token_lst = os.getenv("TEST_SR_GATE_JENKINS_PW", "").split(',')
            name_lst = os.getenv("TEST_SR_GATE_JOB_NAME", "").split(',')
        else:
            print 'In case of %s branch, do nothing!!\n' % refname
            return

        # remote trigger by using file param
        files_dict = {}
        for each_url, each_user, each_token, each_name in \
            zip(url_lst, user_lst, token_lst, name_lst):
            fname = 'TRIGGER_INFO_FILE_' + each_name
            with open(fname, 'w') as f:
                f.write(base64.b64encode(json.dumps(prerelease_description_dict)))

            files_dict[each_name] = [(fname, fname)]
            remote_jenkins_build_job(each_url, each_user, each_token, each_name,
                                     None, None, files_dict[each_name])

    return

def public_trigger_for_tester(events, gerrit_env):
    """ trigger public tester """

    print 'publictrigger_for_tester\n'

    git_prjdir = os.path.join(gerrit_env.gitcache, events['project'])

    # clone_gitproject
    if not clone_gitproject(events['project'], \
                            git_prjdir,
                            gerrit_hostname=gerrit_env.hostname, \
                            gerrit_username=gerrit_env.username, \
                            gerrit_sshport=gerrit_env.sshport):
       print >> sys.stderr, 'Error cloning %s' % events['project']
       return 1

    # get prerelease_description_dict data
    mygit = Git(git_prjdir)
    commit_id = os.getenv("GERRIT_NEWREV")
    arg = commit_id + ':' + GIT_FILE_NAME

    prerelease_description_str = mygit.show(arg)
    prerelease_description_dict = json.loads(prerelease_description_str)
    print json.dumps(prerelease_description_dict, indent=4)

    # set the jenkins info
    refname = os.getenv("GERRIT_REFNAME")
    print 'refname : %s\n' % refname

    public_test_mapping = ast.literal_eval(os.getenv('PUBLIC_TEST_MAPPING'))
    if refname not in public_test_mapping:
        print 'In case of %s branch, do nothing!!\n' % refname
        return

    url_lst = public_test_mapping[refname].get('urls')
    user_lst = public_test_mapping[refname].get('users')
    token_lst = public_test_mapping[refname].get('tokens')
    name_lst = public_test_mapping[refname].get('jobs')

    # remote trigger by using file param
    files_dict = {}
    for each_url, each_user, each_token, each_name in \
        zip(url_lst, user_lst, token_lst, name_lst):
        #print 'each_url(%s), each_user(%s), each_token(%s), each_name(%s)\n' \
        #      % (each_url, each_user, each_token, each_name)
        fname = 'TRIGGER_INFO_FILE_' + each_name

        with open(fname, 'w') as f:
            f.write(base64.b64encode(json.dumps(prerelease_description_dict)))

        files_dict[each_name] = [(fname, fname)]

        print 'Requesting... %s, %s' % (each_url, each_name)
        remote_jenkins_build_job(each_url, each_user, each_token, each_name,
                                None, None, files_dict[each_name])

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

    # get gerrit event
    events = get_gerrit_event()
    if events['host'] == os.getenv('GERRIT_HOSTNAME'):
        if os.getenv("TEST_AUTOMATION_ENABLED", "0") == "1":
            local_trigger_for_tester(events, GerritEnv(""))
    elif events['host'] == os.getenv('PUBLIC_GERRIT_HOSTNAME'):
        # check the envs
        if not os.getenv("PUBLIC_GIT_CACHE_DIR") or \
           not os.getenv("GERRIT_NEWREV") or \
           not os.getenv("PUBLIC_TEST_MAPPING"):
           print 'need to check envs!!\n'
           return

        if os.getenv("PUBLIC_TEST_AUTOMATION_ENABLED", "0") == "1":
            public_trigger_for_tester(get_gerrit_event('PUBLIC_'),
                                     GerritEnv('PUBLIC_')
                                    )
    else:
        print 'need to check envs!!\n'
        return

    return

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

