#!/usr/bin/env python3

import os, sys
from collections import OrderedDict
from ninja_syntax import Writer

_exclusion_list = ['.DS_Store',
                   'autom4te.cache', 'build_windows',
                   'Debug', 'Debug_static', 'Release', 'Release_static',
                   'bin',
                   'docs', 'doc', 'examples', 'test', 'tests']
def _is_excluded(e):
    if e.name in _exclusion_list:
        return True
    if e.name.endswith('-tests'):
        return True
    return False

def collect_files(dirname):
    for e in os.scandir(dirname):
        if _is_excluded(e):
            continue
        if e.is_file():
            yield e.path
        elif e.is_dir():
            yield from collect_files(e.path)


pre_build_commands = [
    'rm -rf "$workdir" "$destdir"',
    'mkdir -p "$workdir"',
    'cp -aR "$srcdir/" "$workdir"',
    'cd "$workdir"',
    ]

post_build_commands = [
    'rm -rf "$workdir"',
    'touch $intdir/$name.done',
    ]

default_build_commands = [
    '$configure $configure_flags',
    'make $makeflags',
    'make install -j1 DESTDIR="$destdir"',
    ]


def gen_configure(n, prj, srcdir=None, configure='configure', flags=[], build_commands=None):
    target = '$intdir/%s.done' % prj
    if not srcdir:
        srcdir = prj
    commands = build_commands if build_commands else default_build_commands
    all_flags = ' '.join(flags)

    configure_commands = pre_build_commands + commands + post_build_commands
    n.rule('%s_build' % prj,
           description='*** BUILD $name ***',
           command=' && '.join(configure_commands))
    n.build([target],
            '%s_build' % prj,
            inputs=list(collect_files(srcdir)),
            variables=OrderedDict([
                ('name', prj),
                ('configure', configure),
                ('configure_flags', all_flags),
                ('srcdir', '$top_srcdir/%s' % srcdir),
                ('destdir', '$builddir/%s' % prj),
                ('workdir', '$intdir/%s' % prj),
            ]))
    return target


with open('build.ninja', 'w') as buildfile:
    n = Writer(buildfile)
    n.comment('generated by %s' % sys.argv[0])
    n.include('build.vars.ninja')

    targets = []

    targets.append(gen_configure(n, 'gettext',
                                 srcdir='gettext',
                                 configure='./configure',
                                 flags=[
                                     '--prefix=/',
                                     'CC=$cc',
                                     'CXX=$cxx',
                                     # When running configure under Xcode,
                                     # SIGALRM is ignored and this doesn't play
                                     # nice with some of the (useless - gnulib)
                                     # checks, resulting in hanging builds.
                                     # See http://comments.gmane.org/gmane.comp.lib.gnulib.bugs/13841
                                     # Let's sabotage the tests by stealing
                                     # alarm() from them.
                                     'CFLAGS="$cflags -Dalarm=alarm_disabled"',
                                     'CXXFLAGS="$cxxflags"',
                                     'LDFLAGS="$ldflags"',
                                     'GSED=$sed',
                                     'YACC=$yacc',
                                     '--with-libiconv-prefix=$SDKROOT/usr',
                                     '--disable-static',
                                     '--disable-java',
                                     '--disable-csharp',
                                     '--disable-rpath',
                                     '--disable-dependency-tracking',
                                     '--enable-silent-rules',
                                     # Needed for the binaries to work on OS X 10.{7,8}:
                                     '--with-included-libxml',
                                 ],
                                 build_commands=[
                                     # Prevent automake regeneration:
                                     'touch `find . -name configure`',
                                     'touch `find . -name aclocal.m4`',
                                     'touch `find . -name config.h.in`',
                                     'touch `find . -name Makefile.in`',
                                     'touch `find . -name *.1`',
                                     'touch `find . -name *.3`',
                                     'touch `find . -name *.html`',
                                     # Prevent running moopp tool that requires GNU sed and refused to be configured to use gsed:
                                     'touch `find . -name *stream*`',
                                     # Prevent running msgfmt:
                                     'touch `find . -name *.gmo`',
                                 ] + default_build_commands + [
                                     # delete unwanted stuff
                                     'rm -f $destdir/bin/{autopoint,envsubst,gettext*,ngettext,recode-sr-latin}',
                                     # fix dylib references to work
                                     '$top_srcdir/../macos/fixup-dylib-deps.sh //lib @executable_path/../lib $destdir/lib $destdir/bin/*',
                                     # strip executables
                                     'strip -S -u -r $destdir/bin/{msgfmt,msgmerge,msgunfmt,msgcat,xgettext}',
                                     'strip -S -x $destdir/lib/lib*.*.dylib',
                                 ]))

    targets.append(gen_configure(n, 'icu',
                                 srcdir='icu4c',
                                 configure='./source/configure',
                                 flags=[
                                     '--prefix=/',
                                     'CC=$cc',
                                     'CXX=$cxx',
                                     'CFLAGS="$cflags -DU_STATIC_IMPLEMENTATION"',
                                     'CXXFLAGS="$cxxflags -DU_STATIC_IMPLEMENTATION"',
                                     'LDFLAGS="$ldflags"',
                                     '--disable-shared',
                                     '--enable-static',
                                     '--with-data-packaging=archive',
                                     '--disable-tests',
                                     '--disable-samples',
                                 ]))

    n.default(targets)

@@ -129,24 +129,51 @@
 .DS_Store',%0A
+                   '.git',%0A
             

Exclude .git files from ninja rules