#!/usr/bin/env python
# vim: ai ts=4 sts=4 et sw=4
#
# 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.
#

import re

"""
APIs used in trbs scripts.
"""

def is_trbs_project(project_name):
    """
    Return true if the project name belong to trbs namespace
    """
    return project_name.startswith("home:trbs:")

def get_trbs_project_name(obs_target_prj, git_tag_name):
    """
    Get trbs OBS project name from gerrit event parameters.

    Prerelease project name format is:
       home:trbs:<origin_target_obs_project>:<tag>

    """
    return "home:trbs:%s:%s" % (obs_target_prj,
                                      git_tag_name.replace('/', ':'))

def get_info_from_trbs_name(trbs_project):
    """
    Get target obs project and tag time stamp

    """
    for tag in (':submit:', ':accepted:', ':submitgroup:'):
        splitted = trbs_project.split(tag)
        if len(splitted) > 1:
            return (':'.join(splitted[0].split(':')[2:]).split(':ref:')[0],
                    ':'.join(splitted[0].split(':')[2:]).split(':ref:')[1],
                    splitted[-1][splitted[-1].find(':',1)+1:])

def get_ref_prj_from_trbs_name(project, tag):
    """
    Get reference obs project
    """
    return (':'.join(project.split(':'+tag.replace('/', ':'))[0].split(':')[2:]))

def trbs_enabled(obs_project):
    """
    Check if trbs is enabled for OBS project.
    This is done by querying repo data from Redis and checking out
    """
    import os

    try:
        if obs_project in os.getenv('TRBS_PROJECTS').split(','):
            return True
        else:
            return False
    except:
        return False
