#!/usr/bin/python
# -*- coding: utf-8 -*-

from optparse import OptionParser
from simple_manager import __version__ as Version

import sys
import subprocess
import yaml
import os

config = None
WORKSPACE = None
project = None

def get_last_tag():
    cmd = 'git describe --tags `git rev-list --tags --max-count=1`'
    cwd = '%s/%s'% (WORKSPACE, config['projects'][project]['name'])

    try:
        tag = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True, cwd=cwd).stdout.read()
        print "Last tag for %s: %s" % (project, tag.replace("\n",""))
    except:
        print "No tags found for %s" % project

def git_clone():
    cmd = ['git', 'clone', config['projects'][project]['repo']]
    print "Cloning %s into %s" % (project, WORKSPACE)
    p = subprocess.Popen(cmd, cwd=WORKSPACE)
    p.wait()

def develop_install():
    cmd = ['python', 'setup.py', 'install', config['projects'][project]['repo']]
    p = subprocess.Popen(cmd, cwd=WORKSPACE)
    p.wait()

def git_update():
    cmd = ['git', 'pull']
    p = subprocess.Popen(cmd, cwd=WORKSPACE+'/'+config['projects'][project]['name'])
    p.wait()
    
def git_push():
    cmd = ['git', 'push']
    p = subprocess.Popen(cmd, cwd=WORKSPACE+'/'+config['projects'][project]['name'])
    p.wait()

def main(argv):
    global config
    global yaml_file
    global WORKSPACE
    global project

    parser = OptionParser(version=Version)
    parser.add_option("-c", "--clone", action="store_true", dest="clone",
                      help="Clone a project")

    parser.add_option("-f", "--file", dest="filename", help="Path do config.yaml",
                      metavar="FILE")

    parser.add_option("-p", "--push", action="store_true", dest="push",
                      help="Push changes to remote repository")

    parser.add_option("-u", "--update", action="store_true", dest="update", help="Update repositories.")

    parser.add_option("-T", "--TAGS", action="store_true", dest="tags",
                      help="Show last tags por all configured repositories")

    parser.add_option("-t", "--tag", dest="tag",
                      help="Tag a repo or all repos, if none tag is provided")

    parser.add_option("-r", "--repo", dest="project", metavar="(PROJECT|all)",
                      help="The project as configured in config.yaml")

    parser.add_option("-d", "--pip-develop", action="store_true", dest="develop",
                      help="Install dependencies in 'develop mode'")

    (options, args) = parser.parse_args()

    if not options.filename:
        print 'You must provide a config.yaml file.'
        sys.exit(2)
    
    yaml_file = options.filename
    config = yaml.load(open(yaml_file, 'r'))
    WORKSPACE = config['workspace']
    
    if options.project:
        project = options.project
        if not config['projects'].get(options.project):
            print "Project '%s' is not configured in config.yaml. Please, verify." % project
            sys.exit(2)
    else:
        project = "all"

    if options.update:
        if project != 'all':
            git_update()
        else:
            print "Updating %s"  % ', '.join(config['projects'].keys())
            for repo in config['projects'].keys():
                project = repo
                git_update()

    elif options.clone:
        if project != 'all':
            git_clone()
        else:
            print "Cloning %s"  % ', '.join(config['projects'].keys())
            for repo in config['projects'].keys():
                project = repo
                git_clone()

    elif options.push:
        if project != 'all':
            git_push()
        else:
            print "Pushing %s"  % ', '.join(config['projects'].keys())
            for repo in config['projects'].keys():
                project = repo
                git_push()

    elif options.tags:
        if project != 'all':
            get_last_tag()
        else:
            print "Getting last tags for %s"  % ', '.join(config['projects'].keys())
            for repo in config['projects'].keys():
                project = repo
                get_last_tag()

    elif options.tag:
        if project != 'all':
            git_tag()
        else:
            print "Tagging projects %s"  % ', '.join(config['projects'].keys())
            #print "User you be promped to enter each desired tag"
            for repo in config['projects'].keys():
                project = repo
                git_tag()

    elif options.develop:
        if project != 'all':
            develop_install()
        else:
            print "Installing projects %s"  % ', '.join(config['projects'].keys())
            for repo in config['projects'].keys():
                project = repo
                develop_install()

if __name__ == "__main__":
    main(sys.argv[1:])

@@ -551,16 +551,35 @@
 n%22,%22%22))%0A
+        return tag%0A
     exce
@@ -582,16 +582,16 @@
 except:%0A
-
         
@@ -1001,24 +1001,58 @@
 t_update():%0A
+    print %22Updating %25s%22 %25 project%0A
     cmd = %5B'
@@ -1180,24 +1180,85 @@
 git_push():%0A
+    print %22Sending changes of %25s to remote server%22 %25 project%0A
     cmd = %5B'
@@ -1348,32 +1348,32 @@
 oject%5D%5B'name'%5D)%0A
-
     p.wait()%0A%0Ade
@@ -1366,24 +1366,416 @@
   p.wait()%0A%0A
+def git_tag():%0A    git_update()%0A    tag = get_last_tag()%0A%0A    new_tag = raw_input(%22Enter new tag: %22)%0A    description = raw_input(%22Enter a description for this tag: %22)%0A%0A    cmd = 'git tag -a %25s -m %22%25s%22' %25 (new_tag, description)%0A    cwd = '%25s/%25s'%25 (WORKSPACE, config%5B'projects'%5D%5Bproject%5D%5B'name'%5D)%0A%0A    subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True, cwd=cwd).stdout.read()%0A    %0A    %0A%0A
 def main(arg

tag operations