#!/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
import json
import re

from common.buildtrigger import trigger_info
from common.git import Git, clone_gitproject
from common.prerelease import is_prerelease_project

from gbp.git.args import GitArgs

GIT_FILE_NAME = 'prerelease.description'

class LocalError(Exception):
    """Local error exception."""
    pass

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

    saved_info = trigger_info(os.getenv('TRIGGER_INFO'))

    project = saved_info.get('obs_url').split('project=')[-1]
    if project is None:
        raise LocalError('Please check the project (%s)' \
                         % (project))
    print '\n\"Title\": \"%s\"' % project

    saved_info = json.dumps(saved_info)

    if not is_prerelease_project(project):
        print '%s is not prerelease project' % project
        return 1

    try:
        target_project, branch = \
            re.search(r'home:prerelease:(.*):submit:(.*):[0-9]{8}.[0-9]{6}', \
                      project).groups()
    except Exception as err:
        raise LocalError('Cannot determine target branch (%s)' % err)

    #TODO: tizen_{profile}_tpk branch hack
    if branch.endswith('_tpk'):
        branch = branch.split('_%s_tpk' % target_project.split(':')[-1].lower())[0]
    print 'We have [%s] [%s]' % (target_project, branch)

    prjdir = os.path.join(os.getenv('WORKSPACE'), \
                          os.path.basename(os.getenv('TEST_TRIGGER_GIT_PATH')))

    if not clone_gitproject(os.getenv('TEST_TRIGGER_GIT_PATH'), prjdir, \
                            git_cache_dir=os.getenv('GIT_CACHE_DIR')):
        print 'Error cloning %s' % os.getenv('TEST_TRIGGER_GIT_PATH')
        return 2

    mygit = Git(prjdir)
    if mygit.has_branch('origin/' + branch, remote = True):
        mygit.checkout(branch)
    else:
        args = GitArgs('--orphan', branch)
        mygit._git_command('checkout', args.args)
        args = GitArgs('-rf', '.')
        mygit._git_command('rm', args.args)
    if os.path.exists(os.path.join(prjdir, GIT_FILE_NAME)):
        mygit.remove_files(GIT_FILE_NAME)
    with open(os.path.join(prjdir, GIT_FILE_NAME), 'w') as mf:
        mf.write(saved_info)
    mygit.add_files(GIT_FILE_NAME, True)
    try:
        mygit.commit_staged('%s' % project)
        mygit.push(repo = 'origin', src = branch)
    except Exception as err:
        print '\n** Commit or push to git error, %s\n' % err
        return 4

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

