#!/usr/bin/env python3
# (c) Zygmunt Krynicki 2005,
# Licensed under GPL, see COPYING for the whole text

import glob
import os
import os.path
try:
    import dbm.gnu as gdbm
except ImportError:
    import gdbm
import subprocess

class ProgramGroup(object):
    def __init__(self, arch, repo):
        self.arch = arch
        self.repo = repo
        self.programs = dict()
    def notice_package(self, package_name, user_visible_program_names):
        for user_visible_program_name in user_visible_program_names:
            if user_visible_program_name not in self.programs:
                self.programs[user_visible_program_name] = set()
            self.programs[user_visible_program_name].add(package_name)
    def write_database(self):
        db = gdbm.open("%s-%s.db" % (self.arch, self.repo), "n")
        for program_name, packages in self.programs.items():
            db[program_name] = "|".join(packages)
        db.close()

def build_binary_databases(basedir=".", currentArchOnly=False):
    myarch = subprocess.Popen(
        ["dpkg","--print-architecture"],
        stdout=subprocess.PIPE,
        universal_newlines=True).communicate()[0].strip()
    groups = dict()
    for data_file in glob.glob("%s/*.data" % basedir):
        with open(data_file) as fd:
            for line in fd:
                line = line.strip()
                if not line or line.startswith("#"):
                    continue
                arch, repo, package_name, executables = line.split('|')
                if (currentArchOnly and arch != "all" and arch != myarch):
                    continue
                group_name = "%s-%s" % (arch, repo)
                if group_name not in groups:
                    groups[group_name] = ProgramGroup(arch, repo)
                user_visible_program_names = [
                    os.path.basename(executable)
                    for executable in executables.split(',')]
                groups[group_name].notice_package(
                    package_name, user_visible_program_names)
    # write it out
    for group in groups.values():
        group.write_database()

if __name__ == "__main__":
    build_binary_databases(currentArchOnly=True)
    
