#!/usr/bin/python3
# encoding=utf-8
#
# Copyright © 2016 Alexandre Detiste <alexandre@detiste.be>
# SPDX-License-Identifier: GPL-2.0-or-later

import glob
import gzip
import os
import sys

scope: set[str] = set()
with open(
    os.path.join(os.environ.get('GDP_BUILDDIR', 'out'), 'bash_completion'),
    'r',
) as bash:
    # keep each even line
    while bash.readline():
        scope |= set(bash.readline().rstrip().split())

# old package names
scope.add('quake2-data')
scope.add('wolf3d-data-wl1')
scope.add('wolf3d-v14-data')
scope.add('rtcw-data')

# add this to compare against other Doom packages
scope.add('doom-wad-shareware')

scope.add('game-data-packager')
scope.add('game-data-packager-runtime')


def process(scope: set[str], distro: str) -> dict[str, int]:
    result: dict[str, int] = dict()
    if len(sys.argv) == 2:
        popcon = '/var/cache/popcon/' + distro + '_' + sys.argv[1] + '.gz'
    else:
        popcon = sorted(glob.glob('/var/cache/popcon/'
                                  + distro + '_*.gz')).pop()

    with gzip.open(popcon, 'rb') as f:
        file_content = f.read().decode('latin1')
    for line in file_content.split('\n'):
        if not line or line[0] in ('#', '-'):
            continue
        try:
            package, _score = line.split()[1:3]
            score = int(_score)
            if package in scope:
                # print("%30s %d" % (package, score))
                result[package] = score
        except ValueError:
            # print(distro,line)
            pass

    return result


debian: dict[str, int] = process(scope, 'debian')


class Game:
    name: str
    score: int

    def __init__(self, name: str, score: int) -> None:
        self.name = name
        self.score = score


games: list[Game] = []
for key in scope:
    game = Game(key, debian.get(key, 0))
    games.append(game)

games = sorted(games, key=lambda k: (-k.score, k.name))

print('Package                                             Debian')
print('------------------------------------------------------------')
for package in games:
    print('%49s %8d' % (package.name, package.score))
