#!/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

sys.path.insert(1, os.path.join(sys.path[0], '..'))

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 main():
    """The main body"""

    trigger_info_data = os.getenv('TRIGGER_INFO')

    if trigger_info_data:
        print 'TRBS test trigger\n'
        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

        test_enabled = os.getenv("TEST_AUTOMATION_ENABLED", "0") != "0"
        if test_enabled:
            # 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
                                 )
        # TRIGGER NEXT SYNC-AWS
        if os.getenv("TRBS_SYNC_AWS_ENABLED", "0") != "0":
            trigger_next('SYNC-AWS', content)
    else:
        print 'PUBLIC test trigger\n'

        # check the envs
        if not os.getenv("PUBLIC_GIT_CACHE_DIR") or \
           not os.getenv("GERRIT_NEWREV") or \
           not os.getenv("PUBLIC_TEST_AUTOMATION_ENABLED") or \
           not os.getenv("PUBLIC_TEST_JENKINS_URL") or \
           not os.getenv("PUBLIC_TEST_JENKINS_USER") or \
           not os.getenv("PUBLIC_TEST_JENKINS_API_TOKEN") or \
           not os.getenv("PUBLIC_TEST_JENKINS_JOB_NAME"):
            print 'need to check envs!!\n'
            return

        events = get_gerrit_event('PUBLIC_')
        gerrit_env = GerritEnv('PUBLIC_')
        git_cache = os.getenv('PUBLIC_GIT_CACHE_DIR')
        git_prjdir = os.path.join(git_cache, 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 refname == 'tizen_3.0':
            url_lst = os.getenv("TEST_JENKINS_URL").split(',')
            user_lst = os.getenv("TEST_JENKINS_USER").split(',')
            token_lst = os.getenv("TEST_JENKINS_PW").split(',')
            name_lst = os.getenv("TEST_JOB_NAME").split(',')
        elif refname == 'tizen':
            url_lst = os.getenv("PUBLIC_TEST_JENKINS_URL").split(',')
            user_lst = os.getenv("PUBLIC_TEST_JENKINS_USER").split(',')
            token_lst = os.getenv("PUBLIC_TEST_JENKINS_API_TOKEN").split(',')
            name_lst = os.getenv("PUBLIC_TEST_JENKINS_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):
            #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)]

            public_test_enabled = int(os.getenv("PUBLIC_TEST_AUTOMATION_ENABLED"))
            if public_test_enabled:
               remote_jenkins_build_job(each_url, each_user, each_token, each_name,
                                        None, None, files_dict[each_name])

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