#!/usr/bin/env python3

"""
This will examine all groups containing packages on the system and check which
packages are missing from them. It can be used to keep groups synchronized with
the repos.

Usage: pkg-check_groups <group name> [<group name>...]
"""

import argparse
from pycman import config

def get_local_group(h, grp):
  try:
    for pkg in h.get_localdb().read_grp(grp)[1]:
      yield pkg
  except TypeError:
    pass

def get_sync_group(h, grp):
  for db in h.get_syncdbs():
    try:
      for pkg in db.read_grp(grp)[1]:
        yield pkg
    except TypeError:
      pass


parser = argparse.ArgumentParser(description='Check pacman group consistency.')
parser.add_argument(
  'groups', metavar='<group name>', nargs='+',
  help='the groups to check'
)
parser.add_argument(
  '--config', metavar='<filepath>', default='/etc/pacman.conf',
  help='Pacman configuration file. Default: %(default)s.'
)


def main(args=None):
  args = parser.parse_args(args)
  grps = args.groups
  h = config.init_with_config(args.config)

  for grp in grps:
    local = dict()
    sync = dict()
    l = 0

    for pkg in get_local_group(h, grp):
      l = max(l, len(pkg.name))
      local[pkg.name] = pkg

    for pkg in get_sync_group(h, grp):
      l = max(l, len(pkg.name))
      sync[pkg.name] = pkg

    local_names = set(local)
    sync_names = set(sync)
    fmt = '    %-' + str(l) + 's  %s'
    print(grp)
    added = sync_names - local_names
    if added:
      print('  in group but not installed')
      for name in added:
        print(fmt % (name, sync[name].desc))
    removed = local_names - sync_names
    if removed:
      print('  removed from group in repos')
      for name in removed:
        print(fmt % (name, sync[name].desc))
    if (not added or removed):
      print('  complete')


if __name__ == '__main__':
  main()
