#!/usr/bin/python3

from __future__ import print_function

import sys
import apt

def normalize_line(line):
    line = line.strip()
    (arch,comp,pkg,bins) = line.split("|")
    bins = bins.split(",")
    bins.sort()
    return "%s|%s|%s|%s" % (arch, comp, pkg, ",".join(bins))

def get_new_and_removed_packages(old_scan_data, new_scan_data):
    
    def pkg_only(line):
        (arch,comp,pkg,bins) = line.split("|")
        return pkg

    old = set()
    new = set()
    #func = normalize_line
    func = pkg_only
    with open(old_scan_data) as old_scan_file:
        for l in map(func, old_scan_file):
            old.add(l)
    with open(new_scan_data) as new_scan_file:
        for l in map(func, new_scan_file):
            new.add(l)
    return (set(new - old), set(old - new))

def get_comp_changes(oldf, newf):
    def pkg_and_comp(line):
        (arch,comp,pkg,bins) = line.split("|")
        return "%s|%s" % (comp,pkg)

    func = pkg_and_comp
    old = {}
    new = {}
    comp_changes = {}
    with open(oldf) as oldfile:
        for l in map(func, oldfile):
            (comp, pkg) = l.split("|")
            old[pkg] = comp
    with open(newf) as newfile:
        for l in map(func, newfile):
            (comp, pkg) = l.split("|")
            new[pkg] = comp
    for (pkg,comp) in old.items():
        if pkg in new and new[pkg] != comp:
            comp_changes[pkg] = (comp, new[pkg])
    return comp_changes

if __name__ == "__main__":
    if len(sys.argv) < 3:
        print("need two files")
        sys.exit(1)
    
    # oldfile, newfile given from commandline
    oldf=sys.argv[1]
    newf=sys.argv[2]
   
    # first check for additions and removals
    (new_pkgs, removed_pkgs) = get_new_and_removed_packages(oldf, newf)
    
    print("--- new packages ---")
    for line in new_pkgs:
        print(line)

    print("\n\n")
    print("--- removed packages ---")
    for line in removed_pkgs:
        print(line)
    
    # now do the component changes
    print("\n\n")
    print("--- changed component ---")
    changes = get_comp_changes(oldf, newf)
    for (pkg, change) in changes.items():
        # change is a tuple with (old_comp, new_comp)
        print("%s changed from '%s' to '%s'" % (pkg, change[0], change[1]))


