#!/usr/bin/env python

import sys
from runtasks.findfile import findfile
from importlib.machinery import SourceFileLoader

if __name__ == '__main__':

    # Parse the global command line options. (Everything before the first task name, which we
    # assume is the first thing that does not have a dash.)
    #
    # ArgumentParser.parse_known_args looked like it did what we want but it will *skip* things
    # it doesn't recognize and grab arguments from tasks.  That makes no sense to me.  We'll
    # use our own task parser by making a "run" task to deal with the global flags.a

    args = None
    # Once we parse out any global options, these will be the args tasks and options that
    # are procesed by `run`.

    def run(help=False, verbose=False, version=False, list=False, filename='tasks.py'):
        global args

        if help:
            print('run [options] task1 [task options] task2 [task options] ...')
            print('')
            print(' -h --help      show this help message and exit')
            print(' -V --version   print version and exit')
            print(' -v --verbose   incrase verbosity')
            print(' -f --filename FILENAME')
            print('                the name of the tasks file to search for')
            return 1

        if version:
            from runtasks import version
            print('runtasks version %s' % version)
            return 1

        # Find the tasks file and load it.

        fqn = findfile(filename=filename)
        l = SourceFileLoader('tasks', fqn)
        m = l.load_module()

        # Find all of the functions in the module marked as tasks.

        tasks = { name: func._task for (name, func) in m.__dict__.items() if hasattr(func, '_task') }

        if list:
            from runtasks.lister import print_list
            print_list(tasks)
            return 1

        # Parse the task arguments.

        from runtasks.parser import parse
        parsed = parse(args, tasks)

        for (task, args) in parsed:
            if verbose == 1:
                print(task.name)
            elif verbose > 1:
                print('-' * 80)
                print('Running', task.name)
                print()

            task.call(args)

            if verbose > 1:
                print()

    from runtasks.tasks import Task
    task = Task(run, flags = {
        'V': 'version',
        'v': 'verbose'
    })

    from runtasks.parser import parse_task
    parsed, args = parse_task(task, sys.argv, [])
    task.call(parsed)
