# encoding: utf-8
from __future__ import print_function

__doc__ = """
Use this script to install frequently used python libraries.

copy the script into an empty folder, e.g. a new folder on the desktop. Then open the Terminal, write "python" and drag the script from the Finder into the Terminal window.
It should look like this:
	python /Path/to/the/Script/InstallLibraries.py

Then hit enter. Please enter your password when asked.

For comments write a mail to support@glyphsapp.com
"""


import urllib2, base64, os, sys, zipfile, shutil, tempfile
import site
from distutils.sysconfig import get_python_lib

Libraries = [("https://github.com/typesupply/vanilla/archive/master.zip", "vanilla.zip", "vanilla-master/Lib/vanilla", "vanilla"),
			 ("https://github.com/robofab-developers/robofab/archive/master.zip", "robofab.zip", "robofab-master/Lib/robofab", "robofab"),
			 ("https://github.com/behdad/fonttools/archive/master.zip", "fonttools.zip", "fonttools-master/Lib/fonttools", "fontTools")
			 ]

#tempPath = os.path.join(os.path.dirname(sys.argv[0]), "download")

tempPath = tempfile.mkdtemp()
if len(tempPath) < 5 or not tempPath.startswith("/var/folders/"):
	raise IOError("Unable to create temp folder: %s" % tempPath)
#tempPath = "/Users/georg/Desktop/Temp"

SidePackage = get_python_lib()
SidePackage = "/Library/Python/2.%d/site-packages" % sys.version_info[1]
os.path.exists(SidePackage)

def downloadLib(LibrarySet):
	if not os.path.exists(tempPath):
		os.makedirs(tempPath)
	req = urllib2.Request(LibrarySet[0])
	try:
		u = urllib2.urlopen(req)
	except urllib2.HTTPError, http_e:
		raise IOError("Error downloading...")
		return
	buffer = u.read()
	if buffer:
		
		f = open(os.path.join(tempPath, LibrarySet[1]), 'wb')
		f.write(buffer)
	else:
		f.close()
		raise IOError("Error saving the file...")
		return
	f.close()
	
	zipfile.ZipFile(os.path.join(tempPath, LibrarySet[1]), "r").extractall(tempPath)

def installingLib(LibrarySet):
	src = os.path.join(tempPath,LibrarySet[2])
	dst = os.path.join(SidePackage, LibrarySet[3])
	if os.path.exists(dst):
		shutil.rmtree(dst)
	print("Installing:", dst)
	shutil.copytree(src, dst)

try:
	for LibrarySet in Libraries:
		downloadLib(LibrarySet)
		installingLib(LibrarySet)
except:
	pass
finally:
	if os.path.exists(tempPath):
		shutil.rmtree(tempPath)

