#!/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

from common import buildmonitor_db

def update_dashboard_db(repo_map):
    if os.getenv('BUILDMONITOR_ENABLED', '0') != '1':
        return

    try:
        buildmonitor_db.connect_db()

        query = 'SELECT id, name, release_name, snapshot_dir FROM main_project WHERE name IN (%s)' % ('%s,' * len(repo_map.keys()))[:-1]
        ret_data = buildmonitor_db.get_multi_values_from_query_data(query, tuple(repo_map.keys()))

        existing_projects = []
        diff_projects = []

        for single in ret_data:
            existing_projects.append(single[1]) #pylint: disable=unsubscriptable-object
            if repo_map[single[1]]['Release'] != single[2] or repo_map[single[1]]['SnapshotDir'] != single[3]: #pylint: disable=unsubscriptable-object
                diff_projects.append(single[1]) #pylint: disable=unsubscriptable-object

        new_projects = [ x for x in repo_map.keys() if x not in existing_projects ]

        print '\nNew Projects:'
        print new_projects
        print '\nExisting Projects:'
        print existing_projects
        print '\nDiff Projects:'
        print diff_projects

        query = 'INSERT INTO main_project (name, fake, release_name, snapshot_dir) ' \
                'VALUES (%s, %s, %s, %s)'
        query_list = []
        for x in new_projects:
            query_list.append((x, 1, repo_map[x]['Release'], repo_map[x]['SnapshotDir']))
        buildmonitor_db.do_many_query(query, query_list)

        query = 'UPDATE main_project SET release_name=%s, snapshot_dir=%s ' \
                'WHERE name=%s LIMIT 1'
        for x in diff_projects:
            query_data = (repo_map[x]['Release'], repo_map[x]['SnapshotDir'], x)
            buildmonitor_db.do_query(query,query_data)

    except Exception as err:
        print repr(err)

    if True:
        buildmonitor_db.disconnect_db()

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')))

    extra_files = []
    for root, dirs, files in os.walk(os.path.dirname(config_file)):
        extra_files.extend([ os.path.join(root, x) for x in files if x.endswith('.yaml') ])
    extra_files.remove(config_file)

    ret = bdb.read_repos(file(config_file, 'r').read(), extra_files=extra_files)

    # Update Dashboard DB
    repo_map = {}

    # Print db contents
    repos = bdb.get_repos()
    for x in repos:
        if 'Project' in repos[x] and 'SnapshotDir' in repos[x] and 'Release' in repos[x]:
            repo_map[repos[x]['Project']] = {'SnapshotDir': repos[x]['SnapshotDir'], \
                                             'Release': repos[x]['Release']}
        print '\n%s\n----' % x
        for k in repos[x]:
            print '  %s: %s' % (k, repos[x][k])

    update_dashboard_db(repo_map)

    return ret

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

    print '---[JOB STARTED: %s ]-------------------------'

    if os.getenv('GERRIT_EVENT_TYPE'):
        event = get_gerrit_event()
    elif os.getenv('GIT_COMMIT'):
        print '\n\nBuilding data from %s\n (%s/%s)\n' \
              % (os.getenv('GIT_URL'), os.getenv('GIT_BRANCH'), os.getenv('GIT_COMMIT'))
        # organization/git_path
        git_project = os.getenv('GIT_URL').split(':')[-1].split('.git')[0]
        if git_project == os.getenv('REPOSYAML_PRJ_GITHUB'):
            return load_repos('repos.yaml')
    else:
        print 'Illegal trigger. Stop building redis db!'
        return -1

    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())

