import os
import glob
import re
import subprocess

import setuptools
import setuptools.command.build_py
import debian.changelog


# Get version from debian/changelog
MINI_BUILDD_VERSION = str(debian.changelog.Changelog(file=open("./debian/changelog", "rb")).version)


class Help2Man():
    def __init__(self, prog, section):
        man_page_file = f"src/{prog}.{section}"
        print(f"I: Generating {man_page_file}...")
        # Hack to get the DESCRIPTION from python script for '--name' argument.
        # W/o this, help2man produces lintian 'manpage-has-useless-whatis-entry'
        name = re.search(r'DESCRIPTION = "(.+?)"', open(f"./src/{prog}").read()).group(1)

        subprocess.check_call(f"help2man --no-info --section {section} --name '{name}' --output {man_page_file} ./src/{prog}", shell=True)

        bash_completion_file = f"share/bash-completions/{prog}"
        print(f"I: Generating {bash_completion_file}...")
        os.makedirs(os.path.dirname(bash_completion_file), exist_ok=True)
        with open(bash_completion_file, "w", encoding="UTF-8") as bash_completion:
            bash_completion.write(f'eval "$(register-python-argcomplete3 --shell=bash "{prog}")"\n')


class BuildPy(setuptools.command.build_py.build_py):
    def run(self):
        init_file = "src/mini_buildd/__init__.py"
        print(f"I: Generating {init_file}...")
        with open(init_file, "w", encoding="UTF-8") as init_py:
            init_py.write(f"""\
# -*- coding: utf-8 -*-

__version__ = "{MINI_BUILDD_VERSION}\"
""")
        Help2Man("mini-buildd", 8)
        Help2Man("mini-buildd-client", 1)
        Help2Man("mini-buildd-dput", 1)

        super().run()


def package_data_files(directory, extensions):
    """Little helper to collect file lists for package_data."""
    package_path = "src/mini_buildd"
    result = []
    for extension in extensions:
        result += [f[len(package_path) + 1:] for f in glob.glob(f"{package_path}/{directory}/**/*.{extension}", recursive=True)]
    return result


setuptools.setup(
    cmdclass={"build_py": BuildPy},
    name="mini-buildd",
    version=MINI_BUILDD_VERSION.replace("+", ".").replace("~", "+"),  # Taint Debian version to make setuptools not warn
    package_dir={'': 'src'},
    description="Mini Debian build daemon",
    author="Stephan Sürken",
    author_email="absurd@debian.org",
    scripts=["src/mini-buildd", "src/mini-buildd-client", "src/mini-buildd-dput"],
    packages=["mini_buildd", "mini_buildd/models"],
    package_data={"mini_buildd":
                  package_data_files("templates", ["html", "txt"])
                  + package_data_files("templatetags", ["py"])
                  + package_data_files("static", ["svg", "css", "js", "ico"])})
