#!/usr/bin/env python

from __future__ import print_function
import os.path
import optparse
import sys

# Try to import project_maker (if it is installed), otherwise assume we're in
# the development directory, and try to add the source directory to the
# path.
try:
    import project_maker.build
except ImportError:
    sys.path.append(os.path.abspath(os.path.join(
        os.path.dirname(__file__), '..'
        )))
    import project_maker.build

# Make sure we're not being imported.
if __name__ != '__main__':
    print(
        'You must run this file as a script, not a module.',
        file=sys.stderr
        )
    sys.exit(-1)

# Create the option parsing structure
usage = 'usage: %prog [options] template destination'
parser = optparse.OptionParser(usage=usage)
parser.add_option(
    '-p', '--parameter', action='append', dest='parameters',
    metavar='PARAMETER',
    help=(
        "Set a name:value parameter to pass to the template renderer. " 
        "The colon is required to separate key and value."
        )
    )
parser.add_option(
    '-i', '--ignore', action='append', dest='ignore', metavar='REGEX',
    default=[],
    help="Add a regular expression of files to ignore."
    )
parser.add_option(
    '-b', '--verbatim', action='append', dest='verbatim', metavar='REGEX',
    default=[],
    help=(
        "Add a regular expression of files not to run through the template "
        "renderer."
        )
    )

# Parse the command line
(options, args) = parser.parse_args()

# Check for enough regular arguments.
if len(args) != 2:
    parser.error("you must specify both a template and destination")
template, destination = args

# Convert any parameters we got
if options.parameters:
    split = [item.split(':') for item in options.parameters]
    parameters = dict(
        [(key.strip(), value.strip()) for key, value in split]
        )
else:
    parameters = {}

# We're ready to build now.
project_maker.build.Builder(
    template, destination,
    parameters, project_maker.build.Builder.STANDARD_IGNORES + options.ignore,
    options.verbatim
    ).run()


