#!/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.
#
"""
This code is called by gerrit-plugin to load the backend config to redis.
"""

import os
import sys
import tempfile

from common.backenddb import BackendDB
from common.gerrit import get_gerrit_event
from common.git import Git, clone_gitproject

from gbp.git.repository import GitRepositoryError

def load_repos(config_file):
    """
    store the repos conf in repos.yaml to redis

    Args:
         config_file (str): the repos.yaml file location
    """

    bdb = BackendDB(os.getenv('REDIS_HOST'),
                    int(os.getenv('REDIS_PORT')))
    return bdb.read_repos(file(config_file, 'r').read())

def main():
    """Script entry point.
    """

    print '---[JOB STARTED: %s ]-------------------------'
    event = get_gerrit_event()

    if event['project'] == os.getenv('REPOSYAML_PRJ'):
        # prepare separate temp directory for each build
        workspace = os.getenv('WORKSPACE')
        tmpdir = tempfile.mkdtemp(prefix=workspace+'/')
        prjdir = os.path.join(tmpdir, event['project'])

        # clone gerrit project to local dir
        if event['refname'].startswith('refs/changes'):
            print "refname start with 'refs/changes/', don't update"
            return 0
        clone_gitproject(event['project'], prjdir)
        mygit = Git(prjdir)
        try:
            mygit.checkout(event['newrev'])
        except GitRepositoryError, err:
            print "Can't find %s " % event['newrev']
            print err
            return 0
        return load_repos(os.path.join(prjdir, 'repos.yaml'))

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