#!/usr/bin/env python

import sys

from importlib import import_module
from pkgutil import iter_modules


# exclude modules from this list
excluded = []
excluded += ['seisflows.solver']
excluded += ['seisflows.system.tiger']
excluded += ['seisflows.workflow.test_optimize']
excluded += ['seisflows.workflow.test_preprocess']

# which modules failed to import?
failed = []


# aliases
fail = False
ignore = True
succeed = True


def check_package(pkgname):
    global failed

    if pkgname in excluded:
        return

    package = import_module(pkgname)
    for _, modname, ispkg in iter_modules(package.__path__):
        if ispkg:
            check_package(pkgname+'.'+modname)
        else:
            status = check_module(pkgname+'.'+modname)
            if status == fail:
                failed += [pkgname+'.'+modname]


def check_module(name):
    if name in excluded:
        return succeed
    try:
        import_module(name)
    except NotImplementedError:
        return ignore
    except:
        return fail
    else:
        return succeed


if __name__ == '__main__':

    # load dummy state
    names = []
    names += ['system']
    names += ['optimize']
    names += ['preprocess']
    names += ['solver']
    names += ['postprocess']
    names += ['workflow']
    for name in names:
        sys.modules[name] = []

    # recursively check package
    check_package('seisflows')

    if failed:
        print 'The following modules failed to import:'
        for name in failed: print '  %s' % name
        print ''
        sys.exit(1)
    else:
        print 'All modules imported successfully.'
        sys.exit(0)


