#!/usr/bin/python3
# -*- mode: python; coding: utf-8 -*-
#
#   apt-printchanges - Print changelog entry before
#   installing/upgrading package
#
#   Copyright (C) 2012, 2019       Evgenii Terechkov <evg@altlinux.org>
#
#   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
import time
import rpm

def getHeaders(filename):
    """Get package name, author, last changelog entry and timestamp for .rpm file.
    """
    try:
        with open(filename) as f:
            ts = rpm.TransactionSet()
            headers = ts.hdrFromFdno(f.fileno())
            Name = headers[rpm.RPMTAG_NAME]
            Author = headers[rpm.RPMTAG_CHANGELOGNAME][0]
            ChangelogEntry = headers[rpm.RPMTAG_CHANGELOGTEXT][0]
            TimeStamp = headers[rpm.RPMTAG_CHANGELOGTIME][0]
    except Exception as msg:
        Name = filename
        Author = Exception
        ChangelogEntry = msg
        TimeStamp = 0
    return (Name,Author,ChangelogEntry, TimeStamp)

def Key(packager,text,timestamp):
    """Format key for packages dict
    """
    keyformat = "%s %s\n%s"
    return keyformat % (time.strftime("* %a %b %d %Y", time.localtime(timestamp)), packager, text)

if __name__ == '__main__':

    filenames = sys.stdin.readlines()
    pkgInfos = [getHeaders(f.rstrip()) for f in filenames]

    try:
        if pkgInfos:
            print('=== apt-printchanges ===')
            changesDict={}
            for pkg, packager, text, timestamp in pkgInfos:
                pkg = pkg.decode()
                packager = packager.decode()
                text = text.decode()
                if Key(packager, text, timestamp) not in changesDict:
                    changesDict[Key(packager, text, timestamp)] = [pkg]
                else:
                    changesDict[Key(packager, text, timestamp)].append(pkg)

            for key, pkgs in list(changesDict.items()):
                print("==%s==\n%s" % (" ".join(pkgs),key))
    except Exception as e:
        print(e)
        sys.exit(0)
