#!/usr/bin/python

# Copyright (C) 2011  Iain Lane
# Copyright (C) 2011  Stefano Rivera

# 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/>.

from __future__ import print_function, unicode_literals

from optparse import OptionParser

from launchpadlib.launchpad import Launchpad


def main():
    parser = OptionParser(usage="usage: %prog [options] output-file")
    parser.add_option(
        "-l", "--launchpad", dest="launchpad_instance", default="production")
    options, args = parser.parse_args()
    if len(args) < 1:
        parser.error("requires output file as argument")
    output = args[0]

    lp = Launchpad.login_with(
        'sync-blacklist', options.launchpad_instance, version='devel')
    ubuntu = lp.distributions['ubuntu']

    devel_series = ubuntu.current_series

    blacklisted_always = devel_series.getDifferencesTo(
        status="Blacklisted always")

    with open(output, "w") as output_file:
        print("""# THIS IS AN AUTOGENERATED FILE
# BLACKLISTED SYNCS ARE NOW STORED IN LAUNCHPAD
# SEE <some URL> FOR THE CODE WHICH GENERATES THIS FILE""", file=output_file)

        authors = {}

        for dsd in blacklisted_always:
            pkg = dsd.sourcepackagename
            comments = devel_series.getDifferenceComments(
                source_package_name=pkg)
            for comment in comments:
                if comment.comment_author_link not in authors:
                    authors[comment.comment_author_link] = (
                        comment.comment_author.name)
                comment_author = authors[comment.comment_author_link]
                comment_text = [c for c in comment.body_text.splitlines()
                                if c and not c.startswith("Ignored")]
                print("# %s: %s" % (comment_author, "\n#".join(comment_text)),
                      file=output_file)
            print("%s\n" % pkg, file=output_file)


if __name__ == '__main__':
    main()
