#!/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 script will pull latest change to local when remote ref updated..
"""

import os
import sys

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

from common.buildmonitor_extention import BuildMonitorExtention
from datetime import datetime

def update_dashboard(full_git_path):

    #Only for ref-updated
    if not os.getenv('GERRIT_EVENT_TYPE', None) \
        or not os.getenv('GERRIT_REFNAME', None) \
        or not os.getenv('GERRIT_NEWREV', None) \
        or not os.getenv('GERRIT_PROJECT', None):
        return

    bm_ext = BuildMonitorExtention()

    git_dir = '%s.git' % os.path.join(os.getenv('GIT_CACHE_DIR'), full_git_path)
    mygit = Git(git_dir)
    refname = os.getenv('GERRIT_REFNAME')
    project = os.getenv('GERRIT_PROJECT')
    newrev = os.getenv('GERRIT_NEWREV')
    account_email = os.getenv('GERRIT_EVENT_ACCOUNT_EMAIL', None)

    is_ref_deleted = False
    if newrev == '0000000000000000000000000000000000000000':
        is_ref_deleted = True

    if refname.startswith('refs/tags/'):
        branch = None
        reference = refname
    else:
        branch = refname
        reference = newrev

    ## Tag and Commit have the same commit info
    if is_ref_deleted != True:
        ret_data = mygit.get_commit_info_from_id(reference)
        commit_id      = ret_data["commit_id"]
        committer      = ret_data["committer"]
        commit_date    = ret_data["commit_date"][:19] #pylint: disable=unsubscriptable-object
        commit_message = ret_data["commit_message"]
        db_git_commit_id = bm_ext.update_git_commit_strict( \
            full_git_path, commit_id, committer, commit_date, commit_message, branch)

    ## Tag
    if refname.startswith('refs/tags/'):
        if is_ref_deleted == True:
            bm_ext.delete_git_tag(full_git_path, reference, os.getenv('GERRIT_OLDREV'), \
                account_email, datetime.now())
        else:
            ret_data = mygit.get_tag_info(refname)
            tag_name    = ret_data["tag_name"]
            tag_rev     = ret_data["tag_rev"]
            tagger      = ret_data["tagger"]
            tag_date    = ret_data["tag_date"][:19] #pylint: disable=unsubscriptable-object
            tag_message = ret_data["tag_message"]
            bm_ext.update_git_tag_strict(db_git_commit_id, tag_name, tag_rev, \
                tagger, tag_date, tag_message)

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

    print '---[JOB STARTED]----------------------------------------'

    events = get_gerrit_event()

    # if project is MAPPING_PRJ, clone full respository, otherwise clone bare
    # ones.
    if events['project'] == os.getenv('MAPPING_PRJ'):
        clone_gitproject(events['project'], \
                os.path.join(os.getenv('GIT_CACHE_DIR'), events['project']))

    # clone gerrit project to local git cache dir
    clone_gitproject(events['project'], '%s.git' % \
            os.path.join(os.getenv('GIT_CACHE_DIR'), events['project']),
            bare=True)

    update_dashboard(events['project'])

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

