#!/usr/bin/env python
#
# Copyright (C) 2016 Samsung
#
#    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 will clone scm/meta/git project, and update it to gerrit system"""

import sys
import os
from common.gerrit import Gerrit, get_gerrit_event
from common.git import fetch_change

import yaml
from common.utils import xml_to_obj

from common.backenddb import BackendDB
from common.mapping import git_obs_map_dryrun

def yaml_load_test(path):
    with open(path, 'r') as fd:
        try:
            yaml.load(fd)
        except Exception as err:
            return '\n\n<< %s >>\n%s' % (os.path.basename(path), err)
    return ''

def xml_load_test(path):
    with open(path, 'r') as fd:
        try:
            xml_to_obj(''.join(fd.readlines()))
        except Exception as err:
            return '\n\n<< %s >>\n%s' % (os.path.basename(path), err)
    return ''

def basic_load_test(path):
    if path.endswith('.yaml'):
        return yaml_load_test(path)
    elif path.endswith('.xml'):
        return xml_load_test(path)
    return ''

def main():

    events = get_gerrit_event()

    if events['event_type'] != 'patchset-created':
        return

    working_dir = os.path.join(os.getenv('WORKSPACE'), \
                               os.path.basename(os.getenv('GERRIT_PROJECT')))

    #fecth and checkout change
    fetch_change(os.getenv('GERRIT_PROJECT'), \
                 working_dir, \
                 events['refspec'])

    error_strings = ''
    for path, subdirs, files in os.walk(working_dir):
        for name in files:
            str_err = basic_load_test(os.path.join(path, name))
            error_strings = '%s%s' % (error_strings, str_err)

    if os.getenv('GERRIT_PROJECT') == os.getenv('REPOSYAML_PRJ'):
        extra_files = []
        for root, dirs, files in os.walk(working_dir):
            extra_files.extend([ os.path.join(root, x) for x in files if x.endswith('.yaml') ])
        extra_files.remove(os.path.join(working_dir, 'repos.yaml'))
        error_strings = '%s%s' % (error_strings, \
                                  BackendDB().read_repos_dryrun( \
                                      file(os.path.join(working_dir, 'repos.yaml'), 'r').read(), \
                                      extra_files=extra_files))
    elif os.getenv('GERRIT_PROJECT') == os.getenv('MAPPING_PRJ'):
        error_strings = '%s%s' % (error_strings, \
                                  git_obs_map_dryrun(working_dir))

    gerrit = Gerrit(os.getenv('GERRIT_HOSTNAME'), \
                    os.getenv('GERRIT_USERNAME'), \
                    os.getenv('GERRIT_SSHPORT'), \
                    int(os.getenv('GERRIT_SILENT_MODE')))

    print 'error_strings=[%s]' % error_strings
    error_strings = error_strings.replace(working_dir, '')
    if error_strings:
        print 'I will give you -1'
        gerrit.review(commit = events['patchset_revision'], \
                      message = 'VALID_CHECK_FAIL\n%s' % error_strings, \
                      verified = -1)
    else:
        print 'I will give you +1'
        gerrit.review(commit = events['patchset_revision'], \
                      message = 'VALID_CHECK_PASS', \
                      verified = 1)

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

