#!/usr/bin/env python

import argparse
import subprocess

def get_pkgs(args):
    return set([line.decode().strip() for line in subprocess.Popen(args, stdout=subprocess.PIPE).stdout])

def main():
    parser = argparse.ArgumentParser(usage="%(prog)s [-h | -r <repo> | -k]")
    parser.add_argument("-r", "--repo", metavar="<repo>", help="use a repo instead of foreign packages (e.g. aurutils)")
    parser.add_argument("-k", "--keep", action="store_true", help="don't unvote uninstalled packages")

    args = parser.parse_args()

    installed = get_pkgs(("pacman",) + (("-Slq", args.repo) if args.repo else ("-Qqm",)))
    voted = get_pkgs(("aur-vote", "-l"))

    # The packages to vote and unvote
    vote = sorted(installed.difference(voted))
    unvote = [] if args.keep else sorted(voted.difference(installed))

    if vote or unvote:
        subprocess.call(("aur-vote", "-a"))

        if vote:
            subprocess.call(("aur-vote", "-v") + tuple(vote))
            print("Voted for:")

            for pkg in vote:
                print(f"    {pkg}")

            if unvote:
                print()

        if unvote:
            subprocess.call(("aur-vote", "-u") + tuple(unvote))
            print("Unvoted:")

            for pkg in unvote:
                print(f"    {pkg}")
    else:
        print("Nothing to do")

if __name__ == "__main__":
    main()
