# -*- coding: utf-8 -*-

import os
import sys
import re
import tarfile

import pip
from setuptools import setup, Extension, find_packages
from distutils.ccompiler import new_compiler
from distutils.command.build_ext import build_ext
from distutils.errors import CCompilerError, DistutilsExecError, DistutilsPlatformError


STATIC_BUILD_DIR = "build/static"
STATIC_LIB_NAME = "quickavro"
STATIC_LIB = "{0}/lib{1}.a".format(STATIC_BUILD_DIR, STATIC_LIB_NAME)


class BuildFailed(Exception): pass


def touch(fname, times=None):
    with open(fname, 'a'):
        os.utime(fname, times)

def pip_install(package):
    pip.main(['install', package])

def download_file(url, path):
    try:
        import requests
    except ImportError:
        pip_install('requests')
        try:
            import requests
        except ImportError:
            sys.stderr.write("Unable to download setup dependencies\n")
    if not os.path.isdir("vendor"):
        os.mkdir("vendor")
    with open(path, 'wb') as f:
        r = requests.get(url)
        if r.status_code != 200:
            raise Exception("{}: {}".format(r.status_code, r.text))
        f.write(r.content)
    return path

def rename_dir(files, name):
    if name is None:
        return files
    for f in files:
        if '/' not in f.path:
            continue
        parts = f.path.split('/', 1)
        f.path = "/".join([name, parts[1]])
    return files

def untar(path, strip=None):
    with tarfile.open(path) as tar:
        tar.extractall("vendor", rename_dir(tar.getmembers(), strip))

def get_version():
    version_regex = re.compile(r'^__version__\s*=\s*[\'"]([^\'"]*)[\'"]', re.MULTILINE)
    with open('quickavro/__init__.py', 'r') as f:
        return version_regex.search(f.read()).group(1)

source_files = [
    {
        "name": "Avro C",
        "version": "1.8.0",
        "url": "https://github.com/apache/avro/archive/release-{0}.tar.gz",
        "dir": "avro",
        "filename": "avro-{0}.tar.gz"
    },
    {
        "name": "Jansson",
        "version": "2.7",
        "url": "https://github.com/akheron/jansson/archive/v{0}.tar.gz",
        "dir": "jansson",
        "filename": "jansson-{0}.tar.gz"
    },
    {
        "name": "Snappy",
        "version": "1.1.3",
        "url": "https://github.com/google/snappy/releases/download/{0}/snappy-{0}.tar.gz",
        "dir": "snappy",
        "filename": "snappy-{0}.tar.gz"
    },
    {
        "name": "zlib",
        "version": "1.2.8",
        "url": "https://github.com/madler/zlib/archive/v{0}.tar.gz",
        "dir": "zlib",
        "filename": "zlib-{0}.tar.gz"
    }
]

def download_source_files():