#!/usr/bin/env python
#
#  Licensed under the Apache License, Version 2.0 (the "License"); 
#  you may not use this file except in compliance with the License. 
#  You may obtain a copy of the License at 
#  
#      http://www.apache.org/licenses/LICENSE-2.0 
#     
#  Unless required by applicable law or agreed to in writing, software 
#  distributed under the License is distributed on an "AS IS" BASIS, 
#  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 
#  See the License for the specific language governing permissions and 
#  limitations under the License. 
#
#
# Create a new skeleton template directory tree
#
import os
import sys
import glob
import shutil
import getpass
import logging
import datetime
from contextlib import closing
from optparse import OptionParser

import pkg_resources
from jinja2 import Template
import jinja2.exceptions

def parse_args():
    usage = "%prog [-t <template_type>] <template_name> [<template_2_name> <template_3_name> ...]"
    parser = OptionParser(usage=usage)

    tmpls_dir = pkg_resources.resource_filename('solrnode.templating', 'templates')
    templates = map(os.path.basename,glob.glob(tmpls_dir+"/*"))
    
    parser.add_option("-t", "--template-type", dest="tmpl_type", default='default',
            help="Template type (Templates available: {0})".format(', '.join(templates)))

    options, args = parser.parse_args()
    
    if not args:
        parser.error("Must supply template name to create. Use -h for usage instructions.")
 
    return parser, (options, args)


def main():
    parser, (options, args) = parse_args()
    logging.basicConfig(
        level = logging.INFO,
        format = "%(levelname)s - %(message)s"
    )

    tmpl_type_dir = pkg_resources.resource_filename('solrnode.templating',
        os.path.join('templates', options.tmpl_type))

    if not os.path.isdir(tmpl_type_dir):
        parser.error("Supplied template type (%s) is invalid." % \
            options.tmpl_type)

    for tmpl_name in args:
        tmpl_dir = tmpl_name
        logging.info("Creating template '%s' [template_type: %s]", tmpl_name, options.tmpl_type)
        try:
            shutil.copytree(tmpl_type_dir, tmpl_name)
        except OSError, exc:
            logging.error("Directory '%s' already exists, not creating template for this name.", 
                tmpl_name)
            return 1
        except Error, exc:
            logging.error("Could not create directory for template '%s'. Check that you have sufficient disk space.",
                tmpl_name)
            return 1
        else:    
            # Inject needed defaults into template manifest
            manifest_env = {
                'template_name': tmpl_name,
                'author_name': getpass.getuser(),
                'created_on': datetime.datetime.now()
            }
            
            with closing(open(os.path.join(tmpl_name, '.template_manifest.tmpl'), "r")) as ifh:
                with closing(open(os.path.join(tmpl_name, '.template_manifest'), "w")) as ofh:
                    Template(ifh.read()).stream(**manifest_env).dump(ofh)
            
            os.remove(os.path.join(tmpl_name, '.template_manifest.tmpl'))
            
        logging.info("All done.")
        return 0

if __name__ == "__main__":
    sys.exit(main())
