#!/usr/bin/env python3
# -*- coding: utf8 -*-

from pycman import config
import argparse
import pyalpm



parser = argparse.ArgumentParser(description='List providers of the given packages.')
parser.add_argument(
  'pkgs', metavar='<pkgname>', nargs='+',
  help='the target dependency'
)
parser.add_argument(
  '-c', '--config', metavar='<path>', default='/etc/pacman.conf',
  help='Pacman configuration file'
)
parser.add_argument(
  '-l', '--local', action='store_true',
  help='Search the local database.'
)



def main(args=None):
  pargs = parser.parse_args(args)
  pkgs = pargs.pkgs
  h = config.init_with_config(pargs.config)
  if pargs.local:
    dbs = [h.get_localdb()]
  else:
    dbs = h.get_syncdbs()


  # This would be much more efficient if pyalpm.find_satisfier were to return
  # a list of providers rather than the first one it finds.
  # Sets were tested in one of the variations but attempting toe remove a
  # package from a set resulted in a key error, whence the use of a dictionary.
  for pkg in pkgs:
    for db in dbs:
      candidates = dict((p.name, p) for p in db.pkgcache)
      providers = list()
      while True:
        provider = pyalpm.find_satisfier(candidates.values(), pkg)
        if provider:
          providers.append(provider)
          del candidates[provider.name]
        else:
          break
      for name in sorted(p.name for p in providers):
        print('{} {}/{}'.format(pkg, db.name, name))


if __name__ == "__main__":
  try:
    main()
  except (KeyboardInterrupt, BrokenPipeError):
    pass

# vim: set ts=4 sw=4 tw=0 noet:
