#!/usr/bin/env python3
import os
import sys
import setuptools
from setuptools import setup
from wheel.bdist_wheel import bdist_wheel
from datetime import datetime
from subprocess import Popen, PIPE
from distutils.util import get_platform
from distutils.core import Extension, Distribution

version_args = list(filter(lambda x: x.startswith('--build='),sys.argv))
if len(version_args) > 1:
    datetime.now().timetuple().tm_yday
    print("only one '--build=<num>.<num>.<num>' parameter can be specified")
    sys.exit(1)

def compute_version( ):
    if len(version_args) != 0:
        version_arg=version_args.pop(0).split("=")[1]
        print (version_arg.split("."))
        (major, minor, patch) = version_arg.split(".")
        return(int(major), int(minor), int(patch))
    else:
        print(os.getcwd())
        proc = Popen( [ "../../scripts/version" ], stdout=PIPE, stderr=PIPE )
        out,err = proc.communicate( )
        print(out)
        (major, minor, patch) = out.decode("utf-8").split(".")
        print((major,minor, patch))
        return(int(major), int(minor), int(patch))

(casaviewer_major,casaviewer_minor, casaviewer_patch) = compute_version( )
casaviewer_version = '%d.%d.%d' % (casaviewer_major,casaviewer_minor,casaviewer_patch)

def all_files( dir ):
    acc = [ ]
    for root, directories, filenames in os.walk(dir):
        r = os.path.join(*root.split(os.sep)[1:])
        for filename in filenames:
            acc.append(os.path.join(r,filename))
    return acc

class BinaryDistribution(Distribution):
    user_options = bdist_wheel.user_options + [
        ('build=', None, 'specify build number') ]

    def initialize_options(self):
        Distribution.initialize_options(self)
        self.build=casaviewer_version

    """Distribution which always forces a binary package with platform name"""
    def has_ext_modules(foo):
        return True

class BdistWheel(bdist_wheel):

    user_options = bdist_wheel.user_options + [
        ('build=', None, 'specify build number') ]

    def initialize_options(self):
        bdist_wheel.initialize_options(self)
        self.build=casaviewer_version

    def finalize_options(self):
        bdist_wheel.finalize_options(self)
        # Mark us as not a pure python package
        self.root_is_pure = False

    def get_tag(self):
        python, abi, plat = bdist_wheel.get_tag(self)
        # We don't contain any python source
        python, abi = 'py3', 'none'
        return python, abi, plat

setup( name="casaviewer", version=casaviewer_version,
       maintainer="Darrell Schiebel",
       maintainer_email="drs@nrao.edu",
       author="CASA development team",
       author_email="aips2-request@nrao.edu",
       distclass=BinaryDistribution,
       url="https://open-bitbucket.nrao.edu/projects/CASA/repos/casaviewer/browse",
       download_url="https://casa.nrao.edu/download/",
       license="GNU Library or Lesser General Public License (LGPL)",
#       packages=setuptools.find_packages(),
       packages=['casaviewer','casaviewer.private', 'casaviewer.gotasks'],
       cmdclass={ 'bdist_wheel': BdistWheel },
       package_data={'casaviewer': all_files('casaviewer/__bin__')},
       install_requires=[ 'grpcio', 'protobuf' ] )