#!/usr/bin/env python


import os
import os.path
import shutil
import toolsconfig


CONFIG = os.path.join('tools', 'tools.cfg')
LIBRARY_SVN_REPOS = 'http://closure-library.googlecode.com/svn/trunk'
LIBRARY_GIT_REPOS = 'https://github.com/jarib/google-closure-library'
COMPILER_SVN_REPOS = 'http://closure-compiler.googlecode.com/files/compiler-latest.zip'


def command_exists(command):
    # TODO: Improve strictness
    with os.popen(command + ' --help') as p:
        return p.read() != ''


def setup_closure_library(config):
    if command_exists('svn'):
        os.system('svn checkout %s %s' % (LIBRARY_SVN_REPOS, config.library_local_root()))
    elif command_exists('git'):
        os.system('git clone %s %s' % (LIBRARY_GIT_REPOS, config.library_local_root()))
    else:
        print '[Error] Git or Subversion not found.'
        print 'Please install one of them to download Closure Library.'
        sys.exit()


def setup_closure_compiler(config):
    os.makedirs('tmp')

    subtool_download = os.path.join('tools', 'sub', 'download.py')
    compiler_zip = os.path.join('tmp', 'compiler.zip')
    os.system('python %s %s %s' % (subtool_download, COMPILER_SVN_REPOS, compiler_zip))

    compiler_root = config.compiler_root()
    os.makedirs(compiler_root)

    subtool_unzip = os.path.join('tools', 'sub', 'unzip.py')
    os.system('python %s %s %s' % (subtool_unzip, compiler_zip, compiler_root))

    shutil.rmtree('tmp')


if __name__ == '__main__':
    basedir = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
    os.chdir(basedir)

    config = toolsconfig.ToolsConfig()
    config.load(CONFIG)

    print 'Downloading Closure Library...'
    setup_closure_library(config)

    print 'Downloading Closure Compiler...'
    setup_closure_compiler(config)

@@ -125,27 +125,27 @@
 g')%0ALIBRARY_
-SVN
+GIT
 _REPOS = 'ht
@@ -150,51 +150,46 @@
 http
+s
 ://c
-losure-library
+ode
 .google
-code
 .com/
-svn/trunk
+p/closure-library/
 '%0ALI
@@ -186,35 +186,35 @@
 brary/'%0ALIBRARY_
-GIT
+SVN
 _REPOS = 'https:
@@ -215,51 +215,51 @@
 http
-s
 ://
-github.com/jarib/google-closure-library
+closure-library.googlecode.com/svn/trunk
 '%0ACO
@@ -541,19 +541,19 @@
 exists('
-svn
+git
 '):%0A    
@@ -571,20 +571,17 @@
 em('
-svn checkout
+git clone
  %25s 
@@ -591,27 +591,27 @@
  %25 (LIBRARY_
-SVN
+GIT
 _REPOS, conf
@@ -653,35 +653,35 @@
 command_exists('
-git
+svn
 '):%0A        os.s
@@ -683,33 +683,36 @@
  os.system('
-git clone
+svn checkout
  %25s %25s' %25 (L
@@ -710,35 +710,35 @@
  %25s' %25 (LIBRARY_
-GIT
+SVN
 _REPOS, config.l

Switch the git repo to the official