#!/usr/bin/python
#
# 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 xml.etree.ElementTree as ET
import sys
import os
import re
import json
import subprocess

from common.utils import sync
from common.gerrit import Gerrit, get_gerrit_event
from common.git import clone_gitproject
from common.git_obs_mapping import GitObsMapping

from common.mapping import git_obs_map_full_list

#================================================================================
# generate_mapping()
#================================================================================
def generate_mapping(prjdir, target_dir):
    mapping = GitObsMapping(prjdir)

    if not os.path.exists(target_dir):
        os.makedirs(target_dir)

    #mapping.print_to_file(os.path.join(target_dir, "mapping.json"))

    branches = mapping.get_branches()
    #mapping.print_pretty()

    arg = ' -b '+' -b '.join(branches)

    git_obs_mapping_info = {}

    #proj_branch_info = gerrit.ls_projects()
    cmd = "ssh -p %s %s@%s gerrit ls-projects %s > proj_list" % (os.getenv('GERRIT_SSHPORT', 29418),
                                                                 os.getenv('GERRIT_USERNAME'),
                                                                 os.getenv('GERRIT_HOSTNAME', "review.tizen.org"),
                                                                 arg)
    subprocess.check_output(cmd, shell=True)
    with open("proj_list", "r") as f:
        for l in f:
            branches_available = l.strip().split(' ')
            gerrit_project = branches_available[-1]
            git_obs_mapping_info[gerrit_project] = {}
            i = -1
            for b in branches:
                i=i+1
                if branches_available[i][0] == '-':
                    continue
                m = mapping.get_git_obs_map(gerrit_project, b)
                if m is not None:
                    for p in m:
                        package = os.path.basename(gerrit_project)
                        if "OBS_package" in m[p]:
                            package = m[p]["OBS_package"]
                        git_obs_mapping_info[gerrit_project][p] = package

    target_filename = os.path.join(target_dir, "mapping.json")

    with open(target_filename, "w") as f:
        f.write(json.dumps(git_obs_mapping_info))

#Handle forked git
def generate_fork_git_mapping(prjdir, target_dir):
    mapping = git_obs_map_full_list()
    git_obs_mapping_fork_info = {}
    for item in mapping:
        # We only care about defined git repositories
        if ('OBS_project' not in item) or (not item.get('OBS_project')) \
            or ('Project_name' not in item) or (not item.get('Project_name')):
            continue
        git_repo = item.get('Project_name')
        package_name = item.get('OBS_package', None)
        if not package_name:
            package_name = os.path.basename(git_repo)
        obs_project = item.get('OBS_project')
        if item.get('Project_name') not in git_obs_mapping_fork_info:
            git_obs_mapping_fork_info[git_repo] = {obs_project: package_name}
        else:
            git_obs_mapping_fork_info[git_repo][obs_project] = package_name

    target_filename = os.path.join(target_dir, "mapping_fork.json")

    with open(target_filename, "w") as f:
        f.write(json.dumps(git_obs_mapping_fork_info))

#Handle ABS git
def generate_abs_git_mapping(prjdir, target_dir):
    mapping = git_obs_map_full_list()
    git_obs_mapping_abs_info = {}
    for item in mapping:
        # We only care about abs tag
        if ('OBS_project' not in item) or (not item.get('OBS_project')) \
            or ('Project_name' not in item) or (not item.get('Project_name')) \
            or ('OBS_staging_project' not in item) or (not item.get('OBS_staging_project')) \
            or (item.get('OBS_staging_project') != 'abs'):
            continue
        git_repo = item.get('Project_name')
        package_name = item.get('OBS_package', None)
        if not package_name:
            package_name = os.path.basename(git_repo)
        obs_project = item.get('OBS_project')
        if item.get('Project_name') not in git_obs_mapping_abs_info:
            git_obs_mapping_abs_info[git_repo] = {obs_project: package_name}
        else:
            git_obs_mapping_abs_info[git_repo][obs_project] = package_name

    target_filename = os.path.join(target_dir, "mapping_abs.json")

    with open(target_filename, "w") as f:
        f.write(json.dumps(git_obs_mapping_abs_info))

#Handle BRANCH-OBS project mapping
def generate_branch_obs_mapping(prjdir, target_dir):
    mapping_list = git_obs_map_full_list()

    list_all = {}
    for item in mapping_list:
        if 'OBS_project' not in item or 'Branch_name' not in item:
            continue
        _branch = item['Branch_name']
        _obs_prj = item['OBS_project']
        if _obs_prj not in list_all:
            list_all[_obs_prj] = []
        for _br in _branch.split(','):
            if _br not in list_all[_obs_prj]:
                list_all[_obs_prj].append(_br)

    target_filename = os.path.join(target_dir, "obs_project_branch_mapping.json")

    with open(target_filename, "w") as f:
        f.write(json.dumps(list_all))

###########################################################
# test code
#target_dir = ".dashboard/git_obs_mapping"
#generate_mapping('.', target_dir)
#exit(0)

###########################################################
# main
GERRIT_PROJECT = os.getenv('GERRIT_PROJECT')
WORKSPACE = os.getenv('WORKSPACE')
GERRIT_HOSTNAME = os.getenv('GERRIT_HOSTNAME')
GERRIT_USERNAME = os.getenv('GERRIT_USERNAME')
GERRIT_SSHPORT = os.getenv('GERRIT_SSHPORT')
GERRIT_SILENT_MODE = int(os.getenv('GERRIT_SILENT_MODE'))

events = get_gerrit_event()

prjdir = os.path.join(WORKSPACE, "git-obs-mapping")
clone_gitproject(GERRIT_PROJECT, prjdir, git_cache_dir="nonexist")
target_dir = ".dashboard/git_obs_mapping"

generate_mapping(prjdir, target_dir)
generate_fork_git_mapping(prjdir, target_dir)
generate_abs_git_mapping(prjdir, target_dir)
generate_branch_obs_mapping(prjdir, target_dir)

sync_dest = os.path.join(os.getenv("IMG_SYNC_DEST_BASE"), "snapshots", target_dir)
# sync to the download server.
sync(target_dir, sync_dest)

