import os
import sys
import warnings
from multiprocessing import Process

try:
    from setuptools.command.install import install as orig_install
    from setuptools import setup
except ImportError:
    from distutils.command.install import install as orig_install
    from distutils.core import setup

try:
    import pwd
except ImportError:
    pwd = None

warnings.filterwarnings('ignore', "Unknown distribution option: 'install_requires'")

try:
    os.remove('MANIFEST')
except OSError:
    pass


packages = []
data_files = {}
source_dir = os.path.dirname(__file__)
for root, dirs, files in os.walk('$package_name'):
    rel_dir = os.path.relpath(root, source_dir)
    data = []
    if '__init__.py' in files:
        for f in files:
            if os.path.splitext(f)[1] not in ['.py', '.pyc', '.pyo']:
                data.append(f)
        package_name = rel_dir.replace(os.sep, '.')
        package_dir = root
        packages.append(package_name)
        data_files[package_name] = data
    else:
        # use previous package name
        filepaths = [os.path.join(root, f) for f in files]
        data_files[package_name].extend([os.path.relpath(f, package_dir) for f in filepaths])

params = dict(
    name='$package_name',
    version='0.0.1',
    packages=packages,
    package_data=data_files,
    url='N/A',
    maintainer='$user',
    maintainer_email='$user@example.com',
    install_requires=[
        'wlauto',
    ],
    # https://pypi.python.org/pypi?%3Aaction=list_classifiers
    classifiers=[
        'Development Status :: 3 - Alpha',
        'Environment :: Console',
        'License :: Other/Proprietary License',
        'Operating System :: Unix',
        'Programming Language :: Python :: 2.7',
    ],
)


def update_wa_packages():
    sudo_user = os.getenv('SUDO_USER')
    if sudo_user:
        user_entry = pwd.getpwnam(sudo_user)
        os.setgid(user_entry.pw_gid)
        os.setuid(user_entry.pw_uid)
    env_root = os.getenv('WA_USER_DIRECTORY', os.path.join(os.path.expanduser('~'), '.workload_automation'))
    if not os.path.isdir(env_root):
        os.makedirs(env_root)
    wa_packages_file = os.path.join(env_root, 'packages')
    if os.path.isfile(wa_packages_file):
        with open(wa_packages_file, 'r') as wfh:
            package_list = wfh.read().split()
            if params['name'] not in package_list:
                package_list.append(params['name'])
    else:  # no existing package file
        package_list = [params['name']]
    with open(wa_packages_file, 'w') as wfh:
        wfh.write('\n'.join(package_list))


class install(orig_install):

    def run(self):
        orig_install.run(self)
        # Must be done in a separate process because will drop privileges if
        # sudo, and won't be able to reacquire them.
        p = Process(target=update_wa_packages)
        p.start()
        p.join()


params['cmdclass'] = {'install': install}


setup(**params)
