#!/usr/bin/python
#
#   apt-printchanges - Print changelog entry before
#   installing/upgrading package
#
#   Copyright (C) 2012       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/>.
#

from __future__ import with_statement
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:
            (headers, _) = rpm.headerFromPackage(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, 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:
                if not changesDict.has_key(Key(packager, text, timestamp)):
                    changesDict[Key(packager, text, timestamp)] = [pkg]
                else:
                    changesDict[Key(packager, text, timestamp)].append(pkg)

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