#!/usr/bin/env python3

import argparse
from pycman import config
import sys
import AUR.PkgList as apl

import logging

parser = argparse.ArgumentParser(description='Search for packages in the repo and the AUR.')
parser.add_argument(
  'pkgs', metavar='<pkg>', nargs='+'
)
parser.add_argument(
  '-c', '--config', default='/etc/pacman.conf',
  help='Pacman configuration file. Default: %(default)s'
)
parser.add_argument(
  '-a', '--aur', action='store_true',
  help='Search the AUR.'
)
parser.add_argument(
  '-f', '--first', action='store_true',
  help='Only return the first location.'
)
parser.add_argument(
  '-q', '--quiet', action='store_true',
  help='Only print the names of found packages.'
)


def add(d, p, l):
  try:
    d[p].append(l)
  except KeyError:
    d[p] = [l]




def main(args=None):
  logging.basicConfig(level=logging.ERROR)

  pargs = parser.parse_args(args)
  if pargs.quiet:
    pargs.first = True


  pkgs = set(pargs.pkgs)
  found = dict()

  h = config.init_with_config(pargs.config)
  for pkg in pkgs:
    for db in h.get_syncdbs():
      if db.get_pkg(pkg):
        add(found, pkg, '[{}]'.format(db.name))
        if pargs.first:
          break;

  if pargs.first:
    pkgs -= set(found)

  if pargs.aur and pkgs:
    aplo = apl.PkgList()
    aplo.refresh()
    aurpkgs = set(aplo)
    for p in pkgs & aurpkgs:
      add(found, p, 'AUR')

    if pargs.first:
      pkgs -= set(found)

  if pargs.quiet:
    for pkg in sorted(found):
      print(pkg)
  else:
    for pkg in sorted(found):
      print(pkg, ' '.join(found[pkg]))



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