#!/usr/bin/python
import sys
import urllib
import os
import zipfile
import glob
cachedir = "../pkg-cache"
srcdir = "../src-cache"

def setup():
    if not os.path.exists(cachedir):
        os.mkdir(cachedir)

def gnome_bin_url(app, ver):
    short_ver = "%s.%s" % (ver.split(".")[0], ver.split(".")[1])
    return "http://ftp.gnome.org/pub/gnome/binaries/win32/%(app)s/%(short_ver)s/%(app)s_%(ver)s_win32.zip" % locals()

def gnome_src_url(app, ver):
    short_ver = "%s.%s" % (ver.split(".")[0], ver.split(".")[1])
    ver = ver.split("-")[0]
    return"http://ftp.gnome.org/pub/gnome/sources/%(app)s/%(short_ver)s/%(app)s-%(ver)s.tar.bz2" % locals()

urls = {}
for app, ver in (("glib", "2.20.1-1"),
     ("gtk+", "2.16.1-1"),
     ("pango", "1.24.0-1"),
     ("atk", "1.24.0-1")):
    urls[app] = {'bin': gnome_bin_url(app, ver),
                 'src': gnome_src_url(app, ver)}
    urls['cairo'] = {
            'bin': "http://ftp.gnome.org/pub/gnome/binaries/win32/dependencies/cairo_1.8.6-1_win32.zip",
            'src': "http://cairographics.org/releases/cairo-1.8.6.tar.gz"}
    urls['zlib'] = {'bin': "http://www.zlib.net/zlib123-dll.zip"}
    urls['gettext-runtime'] = {
          'bin': "http://ftp.gnome.org/pub/gnome/binaries/win32/dependencies/gettext-runtime-0.17-1.zip",
          'src': "http://ftp.gnome.org/pub/gnome/binaries/win32/dependencies/gettext-0.17.tar.gz"}
    urls['libpng'] = {
            'bin': "http://ftp.gnome.org/pub/gnome/binaries/win32/dependencies/libpng_1.2.34-1_win32.zip"}
    urls['libtiff'] = {
            'bin': "http://ftp.gnome.org/pub/gnome/binaries/win32/dependencies/libtiff-3.8.2.zip"}


def get_files():
    for app in urls:
        url = urls[app]['bin']
        fn = os.path.join(cachedir, url.split("/")[-1])
        if not os.path.exists(fn):
            print "Downloading:", fn
            urllib.urlretrieve(url, fn)
        else:
            print "File already here:", fn

def unpack():
    for app in urls:
        f = os.path.join(cachedir, urls[app]['bin'].split("/")[-1])
        print "unzipping:", f
        z = zipfile.ZipFile(f)
        for n in z.namelist():
            if n.endswith("/"):
                continue
            dir = os.path.join("win32", os.path.dirname(n))
            if not os.path.exists(dir):
                os.makedirs(dir)
            outfile = open(os.path.join("win32", n), 'wb')
            outfile.write(z.read(n))
            outfile.close()

setup()
get_files()
unpack()
