#!/usr/bin/python
"""Usage: kid [options] file [args]
Expand a Kid template file.

options:
  -e enc, --encoding=enc
          Specify the output character encoding.
          Default: utf-8
  -h, --help
          Print this help message and exit.
  -o outfile, --output=outfile
          Specify the output file.
          Default: standard output
  -V, --version
          Print the Kid version number and exit.

file:
  filename of the Kid template.

args:
  key=value or other arguments passed to the template.
"""

# Copyright (c) 2004-2005 Ryan Tomayko
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.

import sys
from os.path import dirname, abspath
from getopt import getopt, GetoptError as gerror

try:
  import kid
except ImportError:
  # adjust sys.path if we're running directly within a source distribution
  from os.path import join as joinpath
  from os import access, F_OK
  bin_dir = dirname(__file__)
  lib_dir = abspath(joinpath(bin_dir, '..'))
  if access(joinpath(lib_dir, 'kid', '__init__.py'), F_OK):
    sys.path.insert(0, lib_dir)
  import kid

def main():
  # get options
  try:
    opts, args = getopt(sys.argv[1:], 'e:ho:V',
        ['encoding=', 'help', 'output=', 'version'])
  except gerror, e:
    sys.stderr.write(str(e) + '\n')
    sys.stdout.write(__doc__)
    sys.exit(2)
  enc = 'utf-8'
  outfile = sys.stdout
  for o, a in opts:
    if o in ('-e', '--encoding'):
      enc = a
    if o in ('-o', '--output'):
      outfile = a
    elif o in ('-h', '--help'):
      sys.stdout.write(__doc__)
      sys.exit(0)
    elif o in ('-V', '--version'):
      from kid import __version__
      sys.stdout.write('Kid %s\n' % __version__)
      sys.exit(0)
  if args:
    # get template file
    f = args.pop(0)
    sys.argv = [f]
    # make sure template dir is on sys.path
    path = abspath(dirname(f))
    if not path in sys.path:
      sys.path.insert(0, path)
    # get arguments for the template file
    kw = {}
    while args:
      a = args.pop(0).split('=', 1)
      if len(a) > 1:
        kw[a[0]] = a[1]
      else:
        sys.argv.append(a[0])
    # do not run as __main__ module
    global __name__
    if __name__ == '__main__':
      sys.modules['__kid_main__'] = sys.modules['__main__']
      __name__ = '__kid_main__'
      del sys.modules['__main__']
    # load kid template as __main__ module
    module = kid.load_template(f, name='__main__', cache=0)
    # execute the template and write output
    module.write(outfile, encoding=enc, **kw)
  else:
    sys.stderr.write('kid: no template file specified.\n')
    sys.stderr.write("     try 'kid --help' for usage information.\n")
    sys.exit(2)

if __name__ == '__main__':
  main()
