#!/usr/bin/env python3

import asyncio
import logging

from optparse import OptionParser

from abuildd import __version__
from abuildd.repository import APKBuildRepository


logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)


def banner(options, args):
    logger.info('abuildd-build version {v}'.format(v=__version__))
    logger.info('options: %r; args: %r', options, args)


def update(loop, repo, log):
    loop.run_until_complete(repo.update(log))


def build(loop, repo, targets, output, log):
    return loop.run_until_complete(asyncio.gather(*[repo.build(target, output, log) for target in targets]))[0]


def main():
    parser = OptionParser()
    parser.add_option('-g', '--git-repository', dest='git-repository', metavar='REPO',
                      help='clone APKBUILDs from REPO')
    parser.add_option('-d', '--destination', dest='destination', metavar='PATH',
                      help='path to deposit built packages in')
    parser.add_option('-p', '--parallel', action='store_true', dest='parallel', default=False,
                      help='build targets in parallel')
    parser.add_option('-l', '--log', dest='log', default=None, metavar='FILE',
                      help='log output to FILE')
    options, args = parser.parse_args()

    log = None
    if options.log:
        try:
            log = open(options.log, 'w')
        except Exception as e:
            logger.error('while opening %s:', options.log)
            logger.exception()
            return 1

    if log:
        logging.basicConfig(format='%(asctime)-15s: %(message)s', stream=log)
    else:
        logging.basicConfig(format='%(asctime)-15s: %(message)s')

    banner(options, args)

    if not getattr(options, 'git-repository'):
        logger.error('--git-repository is required')
        return 1

    if not options.destination:
        logger.error('--destination is required')
        return 1

    loop = asyncio.get_event_loop()
    repo = APKBuildRepository.from_url(getattr(options, 'git-repository'))
    update(loop, repo, log)

    if not options.parallel:
        for target in args:
            return build(loop, repo, [target], options.destination, log)
    else:
        build(loop, repo, args, options.destination, log)

    return 0


if __name__ == '__main__':
    exit(main())
