#!/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 script is used to update git-ref-mapping"""

import os
import sys

from common.buildtrigger import trigger_info
from common.git import Git
from common.mapping import git_obs_map, git_obs_map_full_list
from lxml import etree
from common.git import clone_gitproject

XML_DECLARATION = """<?xml version="1.0" encoding="UTF-8" ?>"""

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

    # parameters
    if os.getenv('profile') is not None and os.getenv('release_id') is not None:
        base_project = os.getenv('profile')
        release_id = os.getenv('release_id')
        release_version = release_id.split('_')[-1]
        print 'Manual trigger: %s, %s' % (base_project, release_id)
    else:
        fields = trigger_info(os.getenv('TRIGGER_INFO'))
        profile = fields['profile']
        base_project = fields['base_project']
        release_id = fields['release_id']
        release_version = release_id.split('_')[-1]

    #TODO: FIXME:
    if ':Base' in base_project:
        print '\n** Skip base project!'
        return 0

    prjdir = os.path.join(os.getenv('WORKSPACE'), os.path.basename(os.getenv('REF_MAPPING_PRJ')))
    # clone scm/git-ref-mapping.git
    if not clone_gitproject(os.getenv('REF_MAPPING_PRJ'), prjdir):
        print >> sys.stderr, 'Error cloning %s' % os.getenv('REF_MAPPING_PRJ')
        return -1

    mapping_file = '{0}/git-ref-mapping.xml'.format(prjdir)

    # replace old version to new
    need_update = False
    with open(mapping_file) as mf:
        lines = mf.readlines()
    parser = etree.XMLParser(remove_comments=False)
    tree = etree.fromstring(''.join(lines))

    # replace old version to new
    #TODO: Do not allow auto configuration
    insert_new = False
    for dft in tree.getiterator('branch'):
        for item in dft.getiterator():
            if item.get('OBS_project') == base_project:
                insert_new = False
                orgn_prj = item.get('OBS_project')
                orgn_brch = item.get('name')
                old_ref = item.get('OBS_staging_project')
                new_ref = ':'.join(old_ref.split(':')[:-1]) + ':' + release_version
                if old_ref != new_ref:
                    need_update = True
                    print '  Replace [%s][%s] %s -> %s' % (orgn_prj, orgn_brch, old_ref, new_ref)
                    item.set('OBS_staging_project', new_ref)

    # Insert new target to tizen branch
    if insert_new == True:
        new_branch_list = []
        full_list = git_obs_map_full_list()
        for t in full_list:
            if 'OBS_project' in t and 'Branch_name' in t:
                if t['OBS_project'] == base_project:
                    [ new_branch_list.append(x) for x in t['Branch_name'].split(',') if x not in new_branch_list ]
        print new_branch_list
        for _br in new_branch_list:
            new_ref = base_project + ':ref:' + release_version
            newKid = etree.Element('branch', \
                                   name                = _br, \
                                   OBS_project         = base_project, \
                                   OBS_staging_project = new_ref)
            newKid.tail = '\n        '
            for dft in tree.getiterator('path'):
                dft.insert(-1, newKid)
            print '  Insert %s[%s](%s)' % (base_project, new_ref, _br)

    new_xml_string = XML_DECLARATION + '\n' + etree.tostring(tree)
    print 'After change...\n%s' % etree.tostring(tree)

    # update git repository
    if need_update or insert_new:
        with open(mapping_file, 'w') as mf:
            mf.write(new_xml_string)
        mygit = Git(prjdir)
        mygit.add_files('*', True)
        mygit.commit_staged('%s' % (release_id))
        mygit.push(repo = 'origin', src = 'master')
        print "\"Title\": \"%s\"" % (release_id)
    else:
        print 'No updates for git-ref-mapping.'

if __name__ == '__main__':

    sys.exit(main())

