#!/usr/bin/python
# -*- coding: utf-8 -*-

# python standard library
from os.path import basename

import pisiconfig
import util
from pisibuild import PisiBuild


def doProgress(filename, percent, rate):
    out = '\r%-30.30s %%%3d %d KB/s' % (filename, percent, rate)
    util.information(out)

def main():
    import sys
    import getopt
    
    # wrapper for usage(progname) function
    help = lambda: util.usage(sys.argv[0])

    # getopt magic
    try:
	opts, args = getopt.getopt(sys.argv[1:],"h",["help"])
    except getopt.GetoptError:
	help()
	sys.exit(1)

    for opt, arg in opts:
	if opt == "-h":
	    help()
	    sys.exit(1)

    # pspec(PISI Spec) to be used for package
    pspec = ""

    # TODO: We accept only one pspec file (at a time) currently,
    # but pisi-build may build many packages (pspecs given in order)
    # sequentially.
    if len(args) != 1:
	help()
	raise PisiBuildError, "pisi-build expects one (and only one) pspec file currently"
    else:
	pspec = args[0]

    # doing the real job.
    pb = PisiBuild(pspec)
    util.information("Building PISI package for: %s\n" % pb.spec.sourceName)

    util.information("Fetching source from: %s (be patient)\n" % pb.spec.archiveUri)
    pb.fetchArchive(doProgress)
    util.information("Source archive is stored: %s/%s\n" %(pisiconfig.archives_dir, pb.archiveName))
#     pb.unpackArchive()
#     pb.applyPatches()
#     pb.buildSource()
#     pb.installTarget()
#     pb.buildPisiPackage()
    

if __name__ == "__main__":
    main()
