#!/usr/bin/python3

import pathlib

import click
import git
import requests
import rfc3986


@click.command()
@click.option('-b', '--branch', help='branch to build from')
@click.option('-r', '--rebuild-strategy', help='rebuild strategy to use')
def main(branch, rebuild_strategy):
    """
    Launch module build based on information in working git repository.
    """

    # ensure CentOS CA file is present
    centos_ca = pathlib.Path.home() / '.centos-server-ca.cert'
    if not centos_ca.exists():
        raise click.ClickException('file ~/.centos-server-ca.cert not found')

    # set up git repo object
    try:
        repo = git.Repo()
    except git.InvalidGitRepositoryError:
        raise click.ClickException('working directory is not a git repository')

    # parse origin
    origin = rfc3986.urlparse(repo.remotes.origin.url)

    # ensure repo is in modules namespace
    path = pathlib.PurePath(origin.path)
    if not path.match('/modules/*'):
        raise click.ClickException('git repository is not in modules namespace')

    if not branch:
        if repo.head.is_detached:
            # With a detached head, we technically aren't on a branch, so we need to guess
            # which branch we came from by looking for our current commit in known branches.
            branches = [
                branch.name
                for branch in repo.branches
                for commit in repo.iter_commits(rev=branch)
                if commit == repo.head.commit
            ]
            try:
                [branch] = branches
            except ValueError:
                raise click.ClickException(
                    'head commit appears in multiple branches, cannot guess branch '
                    '(specify manually with `--branch`)'
                )
        else:
            branch = repo.active_branch.name

    # submit build
    payload = {
        'scmurl': f'git+https://{origin.host}{path}?#{repo.head.commit}',
        'branch': branch,
        'owner': 'centos',
    }
    if rebuild_strategy:
        payload['rebuild_strategy'] = rebuild_strategy
    r = requests.post(
        f'https://mbs.mbox.centos.org/module-build-service/1/module-builds/',
        json=payload,
        verify=centos_ca,
    )

    data = r.json()

    if not r.ok:
        error = data['error']
        message = data['message']
        raise click.ClickException(f'{error} - {message}')

    module = data['name']
    stream = data['stream']
    scmurl = data['scmurl']
    state_url = data['state_url']
    print(f'submitted {module}:{stream} to MBS from {scmurl}')


if __name__ == '__main__':
    main()
