#!/usr/bin/python

# FIXME : Allow reading from a sources.list file, parsing into scheme, server, path, codename and components

params = { 'mode':"init" }


import os , sys

import repolib

if sys.argv[1:] :
    if len(sys.argv) > 2 :
        print "Too many arguments"
        print "Usage : %s repo_name" % os.path.basename( sys.argv[0] )
        sys.exit(2)
    repo_name = sys.argv[1]
else :
    print "Usage : %s repo_name" % os.path.basename( sys.argv[0] )
    sys.exit(1)

try :
    repo = repolib.MirrorRepository.new( repo_name )
except Exception , ex :
    print "Exception : %s" % ex
    sys.exit(255)


meta_files = repo.get_metafile( params )

# FIXME : debian - identify error from updated repositories
# FIXME : yum - only errors produce empty output
if not meta_files :
    print "Cannot process, exiting"
    sys.exit(255)

# After verify all the mirroring parameters, it is safe to create directory tree

repo.build_local_tree()

# Once created, we move in the primary metadata file

local_repodata = repo.write_master_file( meta_files )

print repo.info( local_repodata )


download_pkgs = []
_missing = []

for name,subrepo in repo.subrepos.iteritems() :

    print "Scanning %s" % name

    _pkgs , _missing = subrepo.get_package_list( local_repodata , params , {} )
    download_pkgs.extend( _pkgs )


sections = {}
priorities = {}
tags = {}

for pkg in download_pkgs :

    if pkg.has_key('Section') :
        sections[ pkg['Section'] ] = True
    if pkg.has_key('group') :
        sections[ pkg['group'] ] = True

    if pkg.has_key( 'Tag' ) :
        for tag in pkg['Tag'].split(', ') :
            key , val = tag.split('::',1)
            if not tags.has_key( key ) :
                tags[ key ] = {}
            tags[ key ][ val ] = True

    if pkg.has_key( 'Priority' ) :
        priorities[ pkg['Priority'] ] = True

print
print

if sections : print "sections : %s" % " ".join( map( lambda x : x.replace(" ","_") , sections.keys() ) )
if priorities : print "priorities : %s" % " ".join( priorities.keys() )
if tags : print "tags : %s" % map ( lambda x : "%s - %s" % ( x , tags[x].keys() ) , tags.keys() )

