#!/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.
#
"""The job will clone scm/meta/git project, and update it to IRIS"""


import sys
import os
import base64
import argparse

from common.gerrit import Gerrit, get_gerrit_event
from common.git import fetch_change
from common.iris_rest_client import IrisRestClient

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

USERNAME = os.getenv('IRIS_USERNAME')
PASSWORD = base64.b64decode(os.getenv('IRIS_PASSWORDX', ''))
SERVER = os.getenv('IRIS_SERVER')
GERRIT_PROJECT = os.getenv('GERRIT_PROJECT')
OBS_API_USERNAME = os.getenv('OBS_API_USERNAME')
WORKSPACE = os.getenv('WORKSPACE')
GERRIT_HOSTNAME = os.getenv('GERRIT_HOSTNAME')
GERRIT_USERNAME = os.getenv('GERRIT_USERNAME')
GERRIT_SSHPORT = os.getenv('GERRIT_SSHPORT')
GERRIT_SILENT_MODE = int(os.getenv('GERRIT_SILENT_MODE'))


def is_http_ok(status):
    """
    Returns True if HTTP status is OK
    """
    return status >= 200 and status < 300


def scm_check(client, gerrit, events, domains, gittrees):
    """
    Print scm check information and return errors, check successfully
    only when errors's value is zero.
    """
    print '====scm_check===================================='
    result = client.scm_check(domains, gittrees)
    print result
    print '########################################'

    if is_http_ok(result['status']):
        gerrit.review(commit=events['patchset_revision'],
                      message="SCM syntax & semantic check OK",
                      verified=1)
        return 0

    gerrit.review(commit=events['patchset_revision'],
                  message=result['detail'],
                  verified=-1)
    return 1


def scm_update(client, domains, gittrees):
    """Print scm update information"""
    print '====scm update===================================='
    result = client.scm_update(domains, gittrees)
    print result
    print '########################################'
    return 0 if is_http_ok(result['status']) else 1


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

    desc = ("This job can check syntax of domains and git-trees files in "
            "scm/meta/git project and update them to IRIS by call IRIS client "
            "api.")
    parser = argparse.ArgumentParser(description=desc)
    parser.parse_args()

    events = get_gerrit_event()

    if not GERRIT_PROJECT:
        print 'Invalid gerrit project'
        return -1

    proj_path = os.path.join(WORKSPACE, GERRIT_PROJECT)
    # fecth and checkout change
    fetch_change(GERRIT_PROJECT, proj_path, events['refspec'])

    gerrit = Gerrit(GERRIT_HOSTNAME, GERRIT_USERNAME, GERRIT_SSHPORT,
                    GERRIT_SILENT_MODE)

    domains = os.path.join(proj_path, 'domains')
    gittrees = os.path.join(proj_path, 'git-trees')

    client = IrisRestClient(SERVER, USERNAME, PASSWORD)

    if events['event_type'] == 'patchset-created':
        return scm_check(client, gerrit, events, domains, gittrees)
    elif events['event_type'] == 'change-merged':
        return scm_update(client, domains, gittrees)
    else:
        return 1


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