#!/usr/bin/python3
# -*- coding: utf-8 -*-
# Copyright © 2008 Canonical Ltd.
# Author: Scott James Remnant <scott at ubuntu.com>.
# Hacked up by: Bryce Harrington <bryce at ubuntu.com>
# Change merge_changelog to merge-changelog: Ryan Kavanagh
#                                            <ryanakca@kubuntu.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of version 3 of the GNU General Public License 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/>.

# pylint: disable=invalid-name
# pylint: enable=invalid-name

import sys

from debian.changelog import Changelog

from ubuntutools import getLogger

Logger = getLogger()


def usage(exit_code=1):
    Logger.info(
        """Usage: merge-changelog <left changelog> <right changelog>

merge-changelog takes two changelogs that once shared a common source,
merges them back together, and prints the merged result to stdout.  This
is useful if you need to manually merge a ubuntu package with a new
Debian release of the package.
"""
    )
    sys.exit(exit_code)


########################################################################
# Changelog Management
########################################################################


def merge_changelog(left_changelog, right_changelog):
    """Merge a changelog file."""

    with open(left_changelog, encoding="utf-8") as f:
        left_cl = Changelog(f)
    with open(right_changelog, encoding="utf-8") as f:
        right_cl = Changelog(f)

    left_versions = set(left_cl.versions)
    right_versions = set(right_cl.versions)
    left_blocks = iter(left_cl)
    right_blocks = iter(right_cl)

    clist = sorted(left_versions | right_versions, reverse=True)
    remaining = len(clist)
    for version in clist:
        remaining -= 1
        if version in left_versions:
            block = next(left_blocks)
            if version in right_versions:
                next(right_blocks)
        else:
            block = next(right_blocks)

        assert block.version == version

        Logger.info("%s%s", str(block).strip(), "\n" if remaining else "")


def main():
    if len(sys.argv) > 1 and sys.argv[1] in ("-h", "--help"):
        usage(0)
    if len(sys.argv) != 3:
        usage(1)

    left_changelog = sys.argv[1]
    right_changelog = sys.argv[2]

    merge_changelog(left_changelog, right_changelog)
    sys.exit(0)


if __name__ == "__main__":
    main()
