#!/usr/bin/python3

import sys
import subprocess
import apt_pkg

DISTRO = subprocess.check_output(["lsb_release", "-c", "-s"],
                                 universal_newlines=True).strip()

def get_updates():
    pkgs = []
    apt_pkg.init()
    cache = apt_pkg.Cache(None)
    depcache = apt_pkg.DepCache(cache)
    for pkg in cache.packages:
        inst_ver = pkg.current_ver
        cand_ver = depcache.get_candidate_ver(pkg)
        if inst_ver is not None:
            if cand_ver.ver_str == inst_ver.ver_str:
                continue
            record = {"name": pkg.name,
                      "security": isSecurityUpgrade(pkg, depcache),
                      "section": inst_ver.section,
                      "current_version": inst_ver.ver_str if inst_ver else '-',
                      "candidate_version": cand_ver.ver_str if cand_ver else '-',
                      "priority": cand_ver.priority_str}
            pkgs.append(record)
    return pkgs

def isSecurityUpgrade(pkg, depcache):

    def isSecurityUpgrade_helper(ver):
        """ check if the given version is a security update (or masks one) """
        security_pockets = [("Ubuntu", "%s-security" % DISTRO),
                            ("gNewSense", "%s-security" % DISTRO),
                            ("Debian", "%s-updates" % DISTRO)]

        for (f, _) in ver.file_list:
            for origin, archive in security_pockets:
                if (f.archive == archive and f.origin == origin):
                    return True
        return False
    inst_ver = pkg.current_ver
    cand_ver = depcache.get_candidate_ver(pkg)

    if isSecurityUpgrade_helper(cand_ver):
        return True

    for ver in pkg.version_list:
        if (inst_ver and
                apt_pkg.version_compare(ver.ver_str, inst_ver.ver_str) <= 0):
            continue
        if isSecurityUpgrade_helper(ver):
            return True

    return False

def main():
    pkgs = get_updates()
    sys.exit(str(len(pkgs)))

if __name__ == "__main__":
    main()