#!/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.
#
"""
APIs used in prerelease scripts.
"""

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

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

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

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

def get_info_from_prerelease_name(prerelease_project):
    """
    Get target obs project and tag time stamp

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

    raise ValueError("Can't parse %s" % prerelease_project)

def prerelease_enabled(backenddb, obs_project):
    """
    Check if prerelease is enabled for OBS project.
    This is done by querying repo data from Redis and checking out
    if 'PrereleaseDir' key exists there.
    """
    # import the BackendDBError as private, or it will request all jenkins
    #    slaves have redis-python installed
    from common.backenddb import BackendDBError, EntityError

    try:
        repo_name = backenddb.get_obs_repo_map()[obs_project]

        return 'PrereleaseDir' in backenddb.get_repos()[repo_name]
    except (BackendDBError, EntityError):
        return False

def get_tagname_from_prerelease_name(prerelease_project):
    """
    Get tagname from obs project
    """
    project = get_info_from_prerelease_name(prerelease_project)[0]

    return (prerelease_project.split(project)[-1].replace(":","/")[1:])

def is_devbase_project(project_name):
    """
    Return true if the project name belong to prerelease devbase namespace
    """
    return project_name.startswith("home:prerelease:Tizen:Devbase:")

