import sys
import os

sys.path.insert(1, os.path.join(sys.path[0], '..'))

from common.git import Git, clone_gitproject, GitError
from common.gerrit import Gerrit, GerritError
from gbp.git.repository import GitRepositoryError
from time import sleep

def request_github_release_tag(release_version, destination):

    WORKSPACE = os.getcwd()
    git_tools_repo=['tools/mic', 'tools/gbs']
    gerrit = Gerrit('review.tizen.org', 'tizentools', 29418, 0)

    for git_repo in git_tools_repo:
        git_cache = os.path.join(WORKSPACE)
        prjdir = os.path.join(git_cache, git_repo)

        try:
            gitprj = Git(prjdir)
        except GitRepositoryError, err:
            #clone project to local workspace if it doesn't exist in git cache

            localdir = os.path.join(WORKSPACE, git_repo)
            if not clone_gitproject(git_repo, localdir, gerrit_hostname="review.tizen.org", gerrit_username="tizentools", gerrit_sshport=29418, git_cache_dir=WORKSPACE):
                return -1
        gitprj = Git('%s/%s' % (WORKSPACE,git_repo))

        message = 'Release Tools : %s ' % (release_version)

        if destination == "staging":
            release_tag = "staging-released-tools-"+release_version
        else:
            release_tag = "released-tools-"+release_version

        commitid = gitprj.rev_parse('HEAD')

        gitprj.create_tag(release_tag, message, commitid)
        sleep(1)

        remote = 'ssh://%s@%s:%s/%s' % (gerrit.username, gerrit.host, gerrit.port,git_repo)

        print "git_repo : ", git_repo
        print "message : ", message
        print "release_tag : ", release_tag
        print "commitid : ", commitid
        print "remote : ", remote

        try:
            gitprj.push_tag(remote, release_tag)
        except GitRepositoryError, gre:
            print gre
            return -1

def main(option):
    release_version = option[1]
    destination = option[2]
    request_github_release_tag(release_version, destination)
    return 0

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