#!/usr/bin/env python
# Copyright 2010 Bryce Harrington <bryce@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, either version 3 of the License, or
# (at your option) any later version.
#
# 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 lpltk import LaunchpadService

if len(sys.argv) != 2:
    print 'Usage: %s <project-name>' % sys.argv[0]
    sys.exit(1)
project_name = sys.argv[1]

try:
    lp          = LaunchpadService()
    project     = lp.load_project(project_name)
except:
    sys.stderr.write("Could not connect to launchpad\n")
    sys.exit(7)


def truncate(text, max_size):
    if len(text) <= max_size:
        return text
    return text[:max_size].rsplit(' ', 1)[0]+"..."

def get_next_milestone(project):
    next_milestone = None
    for series in project.series:
        if series.status == "Active Development" or series.status == "Pre-release Freeze":
            for milestone in series.active_milestones:
                if not next_milestone or not next_milestone.date_targeted or \
                        milestone.date_targeted < next_milestone.date_targeted:
                    next_milestone = milestone
    if next_milestone:
        return next_milestone
    else:
        return None


next_milestone = get_next_milestone(project)
if not next_milestone:
    print "No milestone coming up"
    sys.exit(0)

for bugtask in project.searchTasks(status = "Fix Committed", milestone = next_milestone):
    bugtask.status = 'Fix Released'
    bugtask.lp_save()
    print "%7s  %s-->Fix Released  %-40s" %(bugtask.bug.id, bugtask.status, truncate(bugtask.bug.title,60) )


sys.exit(0)
