#! /usr/bin/python

# Copyright 2013 Canonical Ltd.
# Author: Andy Whitcroft <apw@canonical.com>

# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; version 3 of the License.
#
# 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/>.

"""Emit a britney record for a package."""

from __future__ import print_function

#from collections import OrderedDict
from optparse import OptionParser

from launchpadlib.launchpad import Launchpad
#from ubuntutools.question import YesNoQuestion

import lputils

def main():
    parser = OptionParser(
        usage="usage: %prog -s suite [options] package [...]")
    parser.add_option(
        "-l", "--launchpad", dest="launchpad_instance", default="production")
    parser.add_option(
        "-n", "--dry-run", default=False, action="store_true",
        help="only show removals that would be performed")
    parser.add_option(
        "-d", "--distribution", default="ubuntu",
        metavar="DISTRIBUTION", help="override in DISTRIBUTION")
    parser.add_option(
        "-s", "--suite", metavar="SUITE", help="override in SUITE")
    parser.add_option(
        "-e", "--version",
        metavar="VERSION", help="package version (default: current version)")
    parser.add_option(
        "-c", "--command", default='unblock',
        help="migration hint command (default: unlock)")

    options, args = parser.parse_args()

    options.launchpad = Launchpad.login_with(
        "mhint", options.launchpad_instance, version="devel")

    # We care about the development series by defaults.
    if hasattr(options, 'suite'):
        ubuntu = options.launchpad.distributions['ubuntu']
        options.suite = ubuntu.current_series.name + '-proposed'

    lputils.setup_location(options)

    if options.command in ('block'):
        fmt = '{cmd} {package}'
    else:
        fmt = '{cmd} {package}/{version}'

    for package in args:
        source = package.split('/')
        try:
            pkg = lputils.find_latest_published_source(options, source[0])
        except:
            print("# {0} not in {1}".format(package, source[0], options.suite))
            continue

        print(fmt.format(cmd=options.command, package=package, version=pkg.source_package_version))


if __name__ == '__main__':
    main()
