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

#================================================================================
# 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 gerrit ls-projects %s > proj_list" % (os.getenv('GERRIT_SSHPORT', 29418),
                                                              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))

###########################################################
# 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()
print(events)

prjdir = os.path.join(WORKSPACE, "git-obs-mapping")

clone_gitproject(GERRIT_PROJECT, prjdir)
target_dir = ".dashboard/git_obs_mapping"

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