#!/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 sys
import os
import re
import json
import subprocess

from common.utils import sync
from common.git_obs_mapping import GitObsMapping
from common.git import clone_gitproject
from jenkinsapi.jenkins import Jenkins

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

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

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

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

    branch_project_map = {}

    #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]
            i = -1
            for b in branches:
                i=i+1
                # skip if no commits for that branch
                if branches_available[i][0] == '-':
                    continue
                if b not in branch_project_map:
                    branch_project_map[b] = []
                branch_project_map[b].append(gerrit_project)


    final_map = {"branches": list(branches), "branch_projects": branch_project_map}

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

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

###########################################################
# test
#prjdir = os.path.join('.')
#target_dir = ".dashboard/branch_project_mapping"
#generate_mapping(prjdir, target_dir)
#exit(0)

###########################################################
# if next job exists, just return.
jenkins = Jenkins(os.getenv("JENKINS_URL_INTERNAL"),
                  os.getenv("JENKINS_USER"),
                  os.getenv("JENKINS_PW"))
job = os.getenv('JOB_NAME')

url = os.path.join(os.getenv("JENKINS_URL_INTERNAL"),
                  "job",
                  job,
                  "api/python")
job_data = jenkins.get_data(url)
if job_data["queueItem"] is not None:
    print "Another queued job exists. exiting..."
    exit(0)

###########################################################
# main
WORKSPACE = os.getenv('WORKSPACE', '.')
MAPPING_PRJ = os.getenv("MAPPING_PRJ", "scm/git-obs-mapping")
GIT_CACHE = os.getenv("GIT_CACHE_DIR")

print "proj = ", MAPPING_PRJ

prjdir = os.path.join(GIT_CACHE, MAPPING_PRJ)
target_dir = ".dashboard/branch_project_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)

