#!/usr/bin/env python3 -B
"""
Script for collecting distribution archives needed for doing a release.

This collects "sdist" and "wheel" archives, the latter for a number of
Python versions (see below).
"""

import subprocess
import os
import sys
import shutil
import fnmatch

from _common_definitions import PY_VERSIONS, TOP_DIR, DIST_DIR, system_report
from _common_definitions import variants, setup_variant

def files_matching(pattern, dirname):
    return fnmatch.filter(os.listdir(dirname), pattern)

_detected_versions = None
def detect_pyversions():
    global _detected_versions
    if _detected_versions is not None:
        return _detected_versions

    result = []
    for ver in PY_VERSIONS:
        if os.path.exists(os.path.join(
            '/Library/Frameworks/Python.framework/Versions', ver)):

            result.append(ver)

    _detected_versions = result
    return _detected_versions


def main():
    if os.path.exists(DIST_DIR):
       shutil.rmtree(DIST_DIR)
    os.mkdir(DIST_DIR)

    # Information about this build:
    system_report(os.path.join(TOP_DIR, "build-info.txt"), detect_pyversions())

    # Collect the list of subprojects to build
    names = ['pyobjc', 'pyobjc-core']
    for nm in sorted(os.listdir(TOP_DIR)):
        if nm.startswith('pyobjc-framework-'):
            names.append(nm)

    failed = []
    for nm in names:
        # Collect sdist archive with most recent python version.
        status = subprocess.call([
            'python{}'.format(detect_pyversions()[-1]), 'setup.py',
                'sdist', '--dist-dir={}'.format(DIST_DIR),
            ],
            cwd=os.path.join(TOP_DIR, nm))
        if status != 0:
            print("WARNING: Building wheel for {} failed".format(nm))
            failed.append((nm, 'sdist', ''))

        for ver in detect_pyversions():
            for variant in variants(ver):
                setup_variant(ver, variant)
                status = subprocess.call([
                    'python{}'.format(ver), 'setup.py',
                        'bdist_wheel', '--dist-dir={}'.format(DIST_DIR),
                    ],
                    cwd=os.path.join(TOP_DIR, nm))

            if status != 0:
                print("WARNING: Building wheel for {} failed (python {})".format(nm, variant))
                failed.append((nm, 'wheel', variant))

    print()
    print("Collected files")
    print("===============")
    print()
    for nm in names:
        if nm == 'pyobjc': continue
        pattern = nm.replace('-', '?') + '-*'
        print("{}:".format(nm))
        for fn in sorted(files_matching(pattern, DIST_DIR)):
            print("  {}".format(fn))
        print()


    if failed:
        print()
        print("Build failures")
        print("==============")
        print()
        for nm, command, ver in failed:
            if ver:
                print(f"{nm} {command}@{ver}")
            else:
                print(f"{nm} {command}")

        sys.exit(0)

    sys.exit(0)

if __name__ == "__main__":
    main()
