#!/usr/bin/env python

from __future__ import print_function

from os.path import dirname, join, exists
from distutils.core import setup

try:
    import pip
    from setuptools.command.install import install as _install
except ImportError:
    pip = None
    from distutils.command.install import install as _install

import sys
import subprocess

setup_dir = dirname(__file__)
version_file = join(setup_dir, 'src', 'hcl', 'version.py')

def _post_install():
    '''Initialize the parse table at install time'''
    import hcl
    from hcl.parser import HclParser
    parser = HclParser()


class install(_install):
    def run(self):
        _install.run(self)
        self.execute(_post_install, (), msg="Generating parse table...")

def get_version():
    d = {}
    with open(version_file) as fp:
        exec(compile(fp.read(), 'version.py', 'exec'), {}, d)
    return d['__version__']

# Automatically generate a version.py based on the git version
if exists(join(setup_dir, '.git')):
    p = subprocess.Popen(["git", "describe", "--tags", "--long", "--dirty=-dirty"],
                         stdout=subprocess.PIPE,
                         stderr=subprocess.PIPE)
    out, err = p.communicate()
    # Make sure the git version has at least one tag
    if err:
        print("Error: You need to create a tag for this repo to use the builder")
        sys.exit(1)

    # Convert git version to PEP440 compliant version
    # - Older versions of pip choke on local identifiers, so we can't include the git commit
    v, commits, local = out.decode('utf-8').rstrip().split('-', 2)
    if commits != '0' or '-dirty' in local:
        v = '%s.post0.dev%s' % (v, commits)
    
    # Create the version.py file
    with open(version_file, 'w') as fp:
        fp.write("# Autogenerated by setup.py\n__version__ = '{0}'".format(v))

with open(join(dirname(__file__), 'README.rst'), 'r') as readme_file:
    long_description = readme_file.read()

install_requires=open(join(setup_dir, 'requirements.txt')).readlines()

# Install ply before we run setup, as using setup_requires is unreliable
if pip is not None:
    pip.main(['install', 'ply==3.4'])

setup(name='pyhcl',
      version=get_version(),
      description='HCL configuration parser for python',
      long_description=long_description,
      author='Dustin Spicuzza',
      author_email='dustin@virtualroadside.com',
      url='https://github.com/virtuald/pyhcl',
      package_dir={'': 'src'},
      packages=['hcl'],
      scripts=["scripts/hcltool"],
      install_requires=install_requires,
      cmdclass={'install': install},
      classifiers=[
        "Development Status :: 5 - Production/Stable",
        "Intended Audience :: Developers",
        "License :: OSI Approved :: Mozilla Public License 2.0 (MPL 2.0)",
        "Operating System :: OS Independent",
        "Programming Language :: Python",
        "Topic :: Text Processing"
      ])


