#!/usr/bin/env python
#
# Copyright (c) 2014, 2015, 2016 Samsung Electronics.Co.Ltd.
#
# 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.
#
"""This job is triggered by gerrit submit ref update event for preloaded app.
   It will generate tizen app package(.tpk) and requests prerelease routine.
"""

import os
import sys
import shutil
import re
import glob
import zipfile
import ast
import base64
import json
import subprocess
from urllib import quote_plus

from datetime import datetime
from random import randint
from time import sleep
import xml.etree.cElementTree as ElementTree

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

from common.utils import parse_link
from common.mapping import git_obs_map
from common.git import Git, clone_gitproject
from common.gerrit import Gerrit, is_ref_deleted, GerritEnv
from common.buildservice import BuildService
from common.prerelease import get_prerelease_project_name
from common.buildtrigger import trigger_info, trigger_next, remote_jenkins_build_job
from common.send_mail import prepare_mail
from common.workflow import find_specfile, parse_specfile
from common.tizen_studio import TizenStudio


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

def main(argv):
    """
    Script entry point.
    """

    print '---[SCRIPT START at %s]---' % str(datetime.now())

    args = os.getenv('TRIGGER_INFO', None)
    trigger_data = trigger_info(args)

    infra = trigger_data.get('infra', 'LOCAL')

    try:
        event_type = trigger_data["event_type"]
        encoded_data = base64.b64encode(json.dumps(trigger_data))
        #FIXME: [Errno 1] _ssl.c:523: error:14090086:SSL routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify failed
        #remote_jenkins_build_job(os.getenv('PUBLIC_JENKINS_URL'), \
        #                         os.getenv('PUBLIC_JENKINS_USER'), \
        #                         os.getenv('PUBLIC_JENKINS_PW'), \
        #                         jobname='update_abs_rbs_for_dashboard', \
        #                         token='ABS_RBS_DASHBOARD', \
        #                         data='EVENT_TYPE=%s&%s="%s"' % (event_type, event_type, quote_plus(encoded_data)))
        jenkins_url = os.getenv('JENKINS_URL').replace("//", "//" + os.getenv('JENKINS_USER') + ":" + os.getenv('JENKINS_PW') + '@')
        if infra == "PUBLIC":
            jenkins_url = os.getenv('PUBLIC_JENKINS_URL').replace("//", "//"
                          + quote_plus(os.getenv('PUBLIC_JENKINS_USER'))
                          + ":" + quote_plus(os.getenv('PUBLIC_JENKINS_PW')) + '@')
        cmd = "curl --insecure -X POST \"%s/job/%s/buildWithParameters?token=%s&EVENT_TYPE=%s&%s=%s\"" \
                % (jenkins_url,
                   'update_abs_rbs_for_dashboard',
                   'ABS_RBS_DASHBOARD',
                   event_type,
                   event_type, quote_plus(encoded_data))
        subprocess.call(cmd, stdout=sys.stdout,
                        stderr=sys.stderr, shell=True)
   
    except Exception as err:
        print repr(err)
        print 'Updating Dashboard Failed'

if __name__ == '__main__':
    sys.exit(main(sys.argv[1:]))

