#!/usr/bin/env python
# qsgen - Quick Site Generator
# Build static sites using Mako templates

# Copyright (c) 2008 Yann Ramin
#
# 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 os
import sys
import shutil
from mako.template import Template
from mako.lookup import TemplateLookup

from pygments import highlight
from pygments.lexers import get_lexer_by_name
from pygments.formatters import HtmlFormatter

# Support library


def pygment(string, lexer = 'python', linenos = False):
    lexer = get_lexer_by_name(lexer)
    formatter = HtmlFormatter(linenos = linenos)
    res = highlight(string, lexer, formatter)
    return res

def pygment_file(file, *args, **kwargs):
    f = open(file, 'r')
    lines = f.readlines()
    f.close()
    s = "".join(lines)
    return pygment(s, *args, **kwargs)


def pygment_style():
    return u"<style type=\"text/css\">" + HtmlFormatter().get_style_defs('.highlight') + u"</style>"



def templateize(file, out_path):
    mlook = TemplateLookup(directories = ['.'])
    templ = mlook.get_template(file)

    actions = {
        'pygment' : pygment,
        'pygment_file' : pygment_file,
        'pygment_style' : pygment_style
        }

    f = open( os.path.join(out_path, file), 'w')
    print >> f, templ.render_unicode(**actions).encode('UTF-8')
    f.close()

def main():
    if len(sys.argv) < 2:
        print "Usage: qsgen.py <outpath> [src]"
        sys.exit(-1)

    out_path = sys.argv[1]
    src_path = '.'
    if len(sys.argv) == 3:
        src_path = sys.argv[2]

    out_path = os.path.abspath(out_path)
    src_path = os.path.abspath(src_path)

    os.chdir(src_path)
    print "qsgen: ",src_path,"to",out_path



    for root, dirs, files in os.walk('.'):
        for file in files:

            # Skip some common file extensions which shouldn't be copied

            if file[0] == '_':
                continue
            if file[-1] == '~':
                continue


            try:
                os.makedirs(os.path.join(out_path, root))
            except:
                pass
            file = os.path.join(root, file)
            print file,
            if file[-4:] != 'html':
                shutil.copyfile(file, os.path.join(out_path, file))
                print '[copy] ->', os.path.join(out_path, file)
                continue

            templateize(file, out_path)
            print '[templ]'

main()
