#!/usr/bin/env python
# Copyright (c) 2013, Luke Maurits <luke@maurits.id.au>
# Published under the terms of the BSD 3-Clause License
# (see LICENSE file or http://opensource.org/licenses/BSD-3-Clause)

import subprocess
import sys

def main():
    try:
        installed = subprocess.check_output("/usr/sbin/pkg_info")
    except OSError as e:
        sys.stderr.write("Couldn't run /usr/sbin/pkg_info: %s\n" % e.strerror)
        sys.exit(1)
    for line in installed.split("\n"):
        if line:
            pkgname = line.split()[0]
            if check_pkg(pkgname):
                print(line)

def check_pkg(pkgname):
    dependers = subprocess.check_output(["/usr/sbin/pkg_info", "-r", pkgname])
    checking = False
    for line in dependers.split("\n"):
        if line == "Full required by list:":
            checking = True
        elif checking and line:
            return False
    return True

if __name__ == "__main__":
    main()
