#!/usr/bin/python3
#
# Copyright (C) 2013 Michael Gilbert <mgilbert@debian.org>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.

import os
import sys
import apt
import subprocess

# produce a file listing from a dsc file
def get_files(dsc):
    import deb822
    files = []
    with open(dsc) as fdsc:
        data = deb822.Dsc(fdsc)
    for info in data['Files']:
        files.append(info['name'])
    return files

# remove old source package files as we go?
cleanup = True

# colorize output?
color = True

# usage info
program_name = os.path.basename(sys.argv[0])
usage = 'usage: %s [ --apt | --initialize | <list of debian packages to be installed> ]'
if len(sys.argv) < 2:
    print(usage%program_name)
    sys.exit(1)

# make sure destination directory exists
if os.getuid() == 0:
    dstdir = '/var/cache/apt/sources'
else:
    dstdir = os.path.expanduser( '~/%s'%program_name )
if not os.path.exists( dstdir ):
    os.mkdir( dstdir )

# set up an appropriate list of packages
cache = apt.Cache()
if '--apt' in sys.argv:
    packages = sys.stdin.read().splitlines()
elif '--initialize' in sys.argv:
    packages = []
    for package in cache:
        if package.is_installed:
            packages.append('%s_0_all.deb'%(package.name))
else:
    packages = sys.argv[1:]

# print a note about what we're doing when there are packages to process
if packages:
    print('%s: fetching source packages'%program_name)

# step through binary packages and download their sources
sources = {}
skip = '%s: skipping differences for src:%s - %s'
for package in packages:
    if package.count('_') != 2 or not package.endswith('.deb'):
        print('error: \'%s\' is not a supported debian package file name'%package)
        sys.exit(1)
    name = os.path.basename(package).split('_')[0]
    installed = cache[name].installed
    candidate = cache[name].candidate
    if installed:
        oldversion = installed.source_version
    else:
        oldversion = '0'
    newversion = candidate.source_version
    source = candidate.source_name
    if source not in sources:
        try:
            candidate.fetch_source(destdir=dstdir, unpack=False)
            sources[source] = (oldversion, newversion)
        except ValueError:
            print(skip%(program_name, source, 'unable to download sources'))
        except:
            print('%s: unhandled error encountered, exiting'%program_name)
            sys.exit()

# step through each source package and do a debdiff
diff = bytes()
for source in sources:
    oldversion,newversion = sources[source]
    if oldversion == '0' or oldversion == newversion:
        print(skip%(program_name, source, 'no prior source available'))
    else:
        installed_dsc = os.path.join(dstdir, '%s_%s.dsc'%(source, oldversion))
        candidate_dsc = os.path.join(dstdir, '%s_%s.dsc'%(source, newversion))
        if os.path.exists(installed_dsc):
            command = ('/usr/bin/debdiff', '--diffstat', installed_dsc, candidate_dsc)
            process = subprocess.Popen(command, stdout=subprocess.PIPE)
            diff += process.communicate()[0]
            if cleanup:
                installed_files = get_files(installed_dsc)
                candidate_files = get_files(candidate_dsc)
                for installed_file in installed_files:
                    if installed_file not in candidate_files:
                        os.remove(os.path.join(dstdir,installed_file))
                os.remove(installed_dsc)

# apply coloring
if color:
    command = ('colordiff-git')
    process = subprocess.Popen(command, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
    diff = process.communicate(diff)[0]

# page results for user to review
if diff:
    command = ('pager','-R')
    process = subprocess.Popen(command, stdin=subprocess.PIPE)
    process.communicate(diff)
