#!/usr/bin/python

"""
Kicks off a recipe build for a branch in Launchpad which has an associated recipe

Copyright (C) 2013 Brendan Donegan

Authors
    Brendan Donegan <brendan.j.donegan@gmail.com>

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License version 3,
as published by the Free Software Foundation.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.
"""

import sys

from launchpadlib.launchpad import Launchpad
from argparse import ArgumentParser

def main():
    parser = ArgumentParser('Invoke a recipe build on specified branch')
    parser.add_argument('branch',
                        help="Unique name of the branch, "
                             "with ~owner/project/branch format")
    parser.add_argument('--recipe', '-r',
                        help="Recipe name to build with. If there is only one "
                             "then that will be used by default, if not then "
                             "this must be specified.")
    args = parser.parse_args()

    lp = Launchpad.login_with(sys.argv[0], 'production')
    branch = lp.branches.getByUniqueName(unique_name=args.branch)
    if not branch:
        parser.error("{branch} was not found in Launchpad.".format(branch=args.branch))

    if branch.recipes.total_size == 0:
        parser.error("{branch} does not have any recipes.".format(branch=args.branch))
    else:
        build_recipe = None

        if branch.recipes.total_size == 1:
            build_recipe = branch.recipes[0]
        elif args.recipe:
            for recipe in branch.recipes:
                if recipe.name == args.recipe:
                    build_recipe = recipe
        else:
            all_recipe_names = [recipe.name for recipe in branch.recipes]
            parser.error("I don't know which recipe from "
                         "{branch} you want to use, specify "
                         "one of '{recipes}' using --recipe".format(
                            branch=args.branch,
                            recipes=', '.join(all_recipe_names)))

        if build_recipe:
            builds = build_recipe.performDailyBuild()
            if builds:
                for build in builds:            
                    series = lp.load(build['distro_series_link'])
                    print("Build started for {series} at: "
                          "{build_link}".format(series=series.name.title(),
                                                build_link=build['web_link']))
            else:
                print("No new builds have been started.")
                pending_builds = build_recipe.pending_builds
                
                if pending_builds.total_size > 0:
                    for build in pending_builds:
                        print("Build pending for {series} at: "
                              "{build_link}".format(series=build.distro_series.name.title(),
                                                    build_link=build.web_link))
                else:
                    print("The most recent changes have already been built in this PPA.")

if __name__ == "__main__":
    sys.exit(main())
