#!/bin/env python
"""buildWeb.py - Build script to create the web site from source.

This creates a directory 'build-web' under the source tree and
populates it with stuff.  (If you run this on the sourceforge server,
it uses a different directory for output.

"""

# Remember to keep this script Python-2.3.4-compatible!
# That's the only version available on shell.sourceforge.net.

import os.path, shutil
import zipfile

parent = os.path.dirname
HERE = parent(os.path.abspath(os.path.normpath(__file__)))
SOURCE_DIR = parent(HERE)
BUILD_DIR = os.path.join(SOURCE_DIR, "build-web-int")
TARGET_DIR = os.path.join(SOURCE_DIR, "build-web")


def buildAll():
    # --- Compilation.  Build stuff in the BUILD_DIR.
    jsFiles = sourceFiles([
        "js/scm/errors.js",
        "js/scm/booleans.js",
        "js/scm/numbers.js",
        "js/scm/objects.js",
        "js/scm/io.js",
        "js/scm/procedures.js",
        "js/scm/parse.js",
        "js/scm/eval.js",
        "js/scm/vm.js",
        "js/scm/lib.js",
        "js/scm/compile.js",
        "js/scm/psyntax.js",
        "js/ui/console.js",
        "js/ui/util.js",
        "js/ui/test.js"
        ])
    linkedJs = buildPath("js/tryscheme.js")
    linkJs(jsFiles, linkedJs)

    testsXml = buildPath("tests/tests.xml")
    convertTestsToXml(sourcePath("tests/tests.txt"), testsXml)

    # --- Deployment.  Wipe out and rebuild the TARGET_DIR tree.
    deleteTree(TARGET_DIR)
    os.umask(0002)  # Allow process to create group-writeable files
    mkdir(TARGET_DIR, mode=02775)
    copyFile(linkedJs, targetPath("htdocs/js/tryscheme.js"))
    copyFile(testsXml, targetPath("htdocs/tests/tests.xml"))
    copyFile(
        sourcePath("js/scm/psyntaxpp.js"),
        targetPath("htdocs/js/scm/psyntaxpp.js"))

    webFiles = [
        "index.html",
        "about.html",
        "style/tryscheme.css",
        "style/docs.css"]
    copyFiles(webFiles, sourcePath("web/htdocs"), targetPath("htdocs"))


# --- path nonsense

def sourceFiles(files):
    return map(sourcePath, files)

def sourcePath(f):
    segments = f.split("/")
    return os.path.join(SOURCE_DIR, *segments)

def buildPath(f):
    segments = f.split("/")
    return os.path.join(BUILD_DIR, *segments)

def targetPath(f):
    segments = f.split("/")
    return os.path.join(TARGET_DIR, *segments)


# --- actions

def deleteTree(d):
    if os.path.isdir(d):
        print "Deleting directory %s..." % d
        shutil.rmtree(d)

def mkdir(d, mode=None):
    if not os.path.isdir(d):
        print "Creating directory %s..." % d
        os.makedirs(d)
        print "done."
    if mode is not None:
        print "Setting mode=0%03o for %s..." % (mode, d)
        os.chmod(d, mode)
        print "done."

def copyFile(srcf, tgtf):
    mkdir(parent(tgtf))
    print "Copying %s to %s..." % (srcf, tgtf),
    shutil.copyfile(srcf, tgtf)
    print "done."

def copyFiles(files, sourceDir, targetDir):
    """ Copy the given list of files from sourceDir to targetDir. """
    for f in files:
        srcf = os.path.join(sourceDir, f)
        tgtf = os.path.join(targetDir, f)
        copyFile(srcf, tgtf)

def linkJs(sourceFiles, tgtf):
    mkdir(parent(tgtf))
    print "Creating %s..." % tgtf
    outf = open(tgtf, "wb")
    for srcf in sourceFiles:
        print "Adding %s..." % srcf
        inf = open(srcf, "rb")
        shutil.copyfileobj(inf, outf)
        inf.close()
    outf.close()
    print "done."

def convertTestsToXml(srcf, tgtf):
    from compileTests import compileTests
    mkdir(parent(tgtf))
    print "Creating %s..." % tgtf
    compileTests(srcf, tgtf)
    print "done."


def main():
    global TARGET_DIR
    from optparse import OptionParser
    parser = OptionParser()
    parser.add_option("-o", "--target-dir", dest="targetDir",
                      help="put resulting web pages, etc. in DIR", metavar="DIR")
    (options, args) = parser.parse_args()
    assert len(args) == 0

    if options.targetDir is not None:
        TARGET_DIR = path(options.targetDir)

    buildAll()

if __name__ == "__main__":
    main()

