#!/usr/bin/env python
# ooolib-python Packager

# We are going to package the version of ooolib-python found in the
# ooolib-python/ directory.

import sys, os, commands
sys.path.insert(0, 'ooolib-python')
import ooolib

# Get the version number for directory creation
newdir = ooolib.version()

def createdir(dir):
    if os.path.isdir(dir):
        print "  Exists: %s/" % dir
        return
    else:
        os.makedirs(dir)
        print "  Created: %s/" % dir

def copyfiles(sdir, tdir, ext=''):
    files = os.listdir(sdir)
    files.sort()
    for file in files:
        sourcefile = os.path.join(sdir, file)
        targetfile = os.path.join(tdir, file)
        # Skip non-files
        if not os.path.isfile(sourcefile): continue
        # determine the extension
        root, sourceext = os.path.splitext(sourcefile)
        if ext and sourceext != ext: continue
        # Make sure the target does not exist
        if (os.path.isfile(targetfile)):
            os.unlink(targetfile)
        # Copy the file
        os.link(sourcefile, targetfile)
        print "  Link: %s" % (targetfile)

# Create root directory
print "Root Directory"
sourcedir = 'ooolib-python'
targetdir = newdir
createdir(targetdir)
copyfiles(sourcedir, targetdir)

# Create ooolib directory
print "ooolib Package Directory"
sourcedir = os.path.join('ooolib-python', 'ooolib')
targetdir = os.path.join(newdir, 'ooolib')
createdir(targetdir)
copyfiles(sourcedir, targetdir, '.py')

# Create examples Directory
print "examples Directory"
sourcedir = os.path.join('ooolib-python', 'examples')
targetdir = os.path.join(newdir, 'examples')
createdir(targetdir)
copyfiles(sourcedir, targetdir, '.py')

# Create package file
print "Building package"
cmd = "tar cvfz %s.tar.gz %s" % (newdir, newdir)
print commands.getoutput(cmd)
