#!/usr/bin/python
# This file is part of Checkbox.
#
# Copyright 2014 Canonical Ltd.
# Written by:
#   Sylvain Pineau <sylvain.pineau@canonical.com>
#
# Checkbox 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.
#
# Checkbox 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 Checkbox.  If not, see <http://www.gnu.org/licenses/>.

"""
Script that creates a new milestone for a Launchpad project.
Meant to be used as part of a checkbox release to the Hardware Certification
public PPA.
"""

import sys

from launchpadlib.launchpad import Launchpad
from argparse import ArgumentParser


def main():
    parser = ArgumentParser('Create a new milestone for a Launchpad project')
    parser.add_argument('project_name', metavar='project-name',
                        help="Unique name of the project")
    parser.add_argument('--series-name', '-s',
                        help="Name of the targetted series, default trunk")
    parser.add_argument('--new-version', '-n',
                        help="New version to use in the recipe "
                             "(for debian changelog) and bzr tags.")
    parser.add_argument('--date-targeted', '-d',
                        help="Date targeted")
    args = parser.parse_args()

    lp = Launchpad.login_with(sys.argv[0], "production")
    series_name = args.series_name if args.series_name else "trunk"
    datetargeted = args.date_targeted if args.date_targeted else "2069-01-01"

    # Find the project
    try:
        project = lp.projects[args.project_name]
    except KeyError:
        raise ValueError('No such project: "%s"' % args.project_name)

    # Find the series
    matching_series = [
        series for series in project.series if series.name == series_name][-1]

    milestone = matching_series.newMilestone(
        name=args.new_version,
        date_targeted=datetargeted)
    print milestone.web_link


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