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

# binary paths
pager_command = '/usr/bin/pager'
debdiff_command = '/usr/bin/debdiff'
diffstat_command = '/usr/bin/diffstat'
colordiff_command = '/usr/bin/colordiff-git'

# usage info
program_name = os.path.basename(sys.argv[0])
usage = 'usage: %s [ --apt | --initialize | <list of package names> ]'
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 = []
    for filename in sys.stdin.read().splitlines():
        info = os.path.basename(filename)[:-4].split('_')
        packages.append('%s:%s'%(info[0],info[-1]))
elif '--initialize' in sys.argv:
    packages = []
    for package in cache:
        if package.is_installed:
            packages.append(package.fullname)
else:
    packages = sys.argv[1:]
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:
    try:
        installed = cache[package].installed
        candidate = cache[package].candidate
    except:
        name = 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 download exception, exiting'%program_name)
            sys.exit()

# avoid diffing in initialization mode
if '--initialize' in sys.argv:
    sys.exit(0)

# step through each source package and do a debdiff
diff = bytes()
message = 'diffstat %s_%s %s_%s\n\n'
havediffstat = os.path.exists(diffstat_command)
for source in sorted(sources, key=sources.get):
    oldversion,newversion = sources[source]
    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 = (debdiff_command, installed_dsc, candidate_dsc)
        process = subprocess.Popen(command, stdout=subprocess.PIPE)
        debdiff = process.communicate()[0]
        if havediffstat:
            command = (diffstat_command, '-q')
            process = subprocess.Popen(command, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
            diffstat = process.communicate(debdiff)[0]
            if diffstat:
                diff += bytes(message%(source, oldversion, source, newversion), 'utf-8')
                diff += diffstat
                diff += bytes('\n', 'utf-8')
        diff += debdiff
        if cleanup and oldversion != newversion:
            print('%s: removing old src:%s %s'%(program_name, source, oldversion))
            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)
    else:
        if oldversion == '0':
            print(skip%(program_name, source, 'no prior source available'))
        else:
            print(skip%(program_name, source, 'differences already seen'))

# apply coloring
if color:
    command = (colordiff_command)
    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_command,'-R')
    process = subprocess.Popen(command, stdin=subprocess.PIPE)
    process.communicate(diff)
