#!/usr/bin/env python
from __future__ import absolute_import
from __future__ import print_function

import sys, os, posixpath
from glob import glob
import opkg
import getopt
import re

verbose = 0

def usage():
     sys.stderr.write("%s [-p Packages] package ...\n" % (sys.argv[0],))
     sys.exit(-1)

packages_filename = "Packages"
(opts, remaining_args) = getopt.getopt(sys.argv[1:], "hp:")
for (optkey, optval) in opts:
     if optkey == '-h': 
          usage()
     if optkey == '-p': 
          packages_filename = optval

if ( not remaining_args ):
     usage()

packages = opkg.Packages()
packages.read_packages_file(packages_filename)

required = {}
provider_hash = {}

def split_list(str):
     r = []
     l = str.split(",")
     for i in l:
          ll = i.split("|")
          for ii in ll:
               ii = ii.strip()
               r.append(ii)
     return r

for i in list(packages.packages.keys()):
     p = packages.packages[i]
     if p.package not in provider_hash:
          provider_hash[p.package] = []
     provider_hash[p.package].append(p)
     if p.provides:
          provides = p.provides.split(",")
          for prov in provides:
               prov = prov.strip()
               if prov not in provider_hash:
                    provider_hash[prov] = []
               provider_hash[prov].append(p)

def find_package(name):
     # Return all providers of the named package
     if name in provider_hash:
          return provider_hash[name]
     return None

def process_dep(pkg, dep):
     # Add a provider of the given dependency to the list of required packages
     # unless a provider is already present in this list.
     dep = re.sub("\s*\(.*\)", "", dep)
     dep = re.sub("\*$", "", dep)
     newpkgs = find_package(dep)
     if newpkgs:
          # Loop over all providers of the dependency and return early if any
          # provider is already in the list of required pacakges - we only need
          # one provider of this dependency.
          for newpkg in newpkgs:
               if newpkg.package in required:
                    return
          # Select the first provider, add it to the required packages list and
          # process its dependencies
          recurse(newpkgs[0])
     else:
          sys.stderr.write("unsatisfied dependency of %s on '%s'\n" % (pkg.package, dep))

def recurse(pkg):
     # Add a package to the required list and process its dependencies
     required[pkg.package] = 1
     if pkg.depends:
          deps = split_list(pkg.depends)
          for dep in deps:
               process_dep(pkg, dep)

for root in remaining_args:
     pkgs = find_package(root)
     if not pkgs:
          sys.stderr.write("Can't find root package '%s'\n" % root)
          sys.exit(-1)
     for p in pkgs:
          recurse(p)
     
for pkg in list(required.keys()):
     print(pkg)

