#!/usr/bin/env python
# encoding: utf-8
# Created On: Tue 28 Aug 2012 11:44:05  CEST
# Last Modified: Tue 21 Mar 2017 08:40:17 pm CET 
# MAKEFILE for compiling LaTeX Files

VERSION='1.0.0'
APPNAME='MAKEFILE FOR LaTeX'

top='.'
out='build'
chapterpath='./chapters'

# query the options that are possible outputs
def options(ctx):
    ctx.add_option('--form',action='store',default='pdflatex',help='Specify the output format. Allowed values are: pdflatex, latex, htlatex, oolatex, epub, handlatex')
    ctx.add_option('--cover',action='store',help='Specify an image as cover for ePubs.\nOnly works with --form=epub')
    ctx.add_option('--infile',action='store',help='Specify the tex file to use as input file.\nIf not given, all files in the top level directory will be compiled.')
    ctx.add_option('--spellckpath',action='store',help='Specify the path in which to look for the content files for spellcheck.\nDefault is ./chapters',default=chapterpath);

# configure script
def configure(ctx):
    # local functions to configure the selected element
    def find_tex_files(path):
        import os
        ret = []
        for name in os.listdir(path):
            if os.path.isfile(os.path.join(path,name)):
                if (name.endswith('.tex')) or (name.endswith('.ltx')):
                    ret.append(name)
        return ret

    def conf_tex(ctx):
        ctx.load('tex')

    def conf_htlatex(ctx):
        ctx.find_program('mk4ht',var='TEX')
        ctx.env.TEXINPUT = ctx.path.abspath() + '//'
        
    def conf_epub(ctx):
        ctx.find_program('mk4ht',var='TEX')
        ctx.find_program('ebook-convert',var='EPUB')
        ctx.env.TEXINPUT = ctx.path.abspath() + '//'

    def conf_handlatex(ctx):
        ctx.find_program('handlatex',var='TEX')
        ctx.env.TEXINPUT = ctx.path.abspath() + '//'

    # define a structure to assign the functions to the parameters
    conf_output = {'pdflatex' : conf_tex,
              'latex' : conf_tex,
              'htlatex'  : conf_htlatex,
              'oolatex'   : conf_htlatex,
              'epub'  : conf_epub,
              'handlatex' : conf_handlatex

    }

    # set the selected mode
    if ctx.options.form:
        ctx.env.FORM = ctx.options.form
        conf_output[ctx.env.FORM](ctx)
    else:
        ctx.fatal('Output format is not set!')

    # set a cover image
    if ctx.options.cover:
        ctx.env.COVER = ctx.options.cover
    else:
        ctx.env.COVER = ''

    # find the aspell program
    ctx.find_program('aspell',var='ASPELL')

    # set a default path to look for spellck sources
    if ctx.options.spellckpath:
        ctx.env.SPELLCK = ctx.options.spellckpath

    # Set a list of all files to use
    if ctx.options.infile:
        sf = []
        sf.append(ctx.options.infile)
        ctx.env.SOURCEFILES = sf
    else:
        ctx.env.SOURCEFILES = find_tex_files(top)


def build(ctx):
    # metadata parameters
    def build_metadata(fileName,cover):
        ret = '--level1-toc \'//*[@class="title"]\' '
        with open(fileName,'r') as in_file:
            count = 0
            for line in in_file:
                if '% Author' in line:
                    ret += ' --authors "' + line.split(':')[1].rstrip().lstrip() +'"'
                    count += 1
                elif '% Title' in line:
                    ret += ' --title "' + line.split(':')[1].rstrip().lstrip() + '"'
                    count += 1
                elif count > 1:
                    break
            in_file.close()

            if cover:
                ret += ' --cover "' + cover + '"'

            return ret
            
    # local functions to control the build process
    def build_tex(ctx):
        import os
        for f in ctx.env.SOURCEFILES:
            ctx(features = 'tex',
                type     = ctx.env.FORM,
                source   = f,
                prompt   = 0
                )
            if ctx.cmd == 'install':
                outExt = '.dvi'
                if ctx.env.FORM == 'pdflatex':
                    outExt = '.pdf'
                fileName, fileExt = os.path.splitext(f)
                ctx.install_files('${PREFIX}',fileName + outExt)

    def build_htlatex(ctx):
        import os
        for f in ctx.env.SOURCEFILES:
            fileName, fileExt = os.path.splitext(f)
            ctx(rule='TEXINPUTS=${TEXINPUT}: ${TEX} ${FORM} ${SRC} >/dev/null',source=f, target=fileName + '.html')
            if ctx.cmd == 'install':
                fileName, fileExt = os.path.splitext(f)
                ctx.install_files('${PREFIX}',fileName + '.html')

    def build_epub(ctx):
        import os
        for f in ctx.env.SOURCEFILES:
            print(ctx.path.find_resource(ctx.env.COVER))
            if ctx.env.COVER :
                ctx.env.META = build_metadata(f,ctx.path.find_resource(ctx.env.COVER).abspath())
            else:
                ctx.env.META = build_metadata(f,'')
            fileName, fileExt = os.path.splitext(f)
            ctx(rule='TEXINPUTS=${TEXINPUT}: ${TEX} htlatex ${SRC} >/dev/null',source=f, target=fileName + '.html')
            ctx(rule='${EPUB} ${SRC} ${TGT} ${META}',source=fileName + '.html', target=fileName + '.epub')
            if ctx.cmd == 'install':
                ctx.install_files('${PREFIX}',fileName + '.epub')

    def build_handlatex(ctx):
        import os
        for f in ctx.env.SOURCEFILES:
            ctx(rule='TEXINPUTS=${TEXINPUT}: ${TEX} ${SRC} >/dev/null && rm -f ../*.h*',source=f)
            if ctx.cmd == 'install':
                fileName, fileExt = os.path.splitext(f)
                ctx.install_files('${PREFIX}',fileName + outExt)
                

    # define a structure to assign the functions to the parameters
    build_output = {'pdflatex'   : build_tex,
            'latex' : build_tex,
            'htlatex'  : build_htlatex,
            'oolatex'   : build_htlatex,
            'epub'  : build_epub,
            'handlatex' : build_handlatex
    }

    # call the configured build method
    build_output[ctx.env.FORM](ctx)


# Custom command to spellcheck all 
def spellck(ctx):

    # Search for all possible TEX files
    def find_tex_files(path):
        import os
        ret = []
        for root, dirs, files in os.walk(path):
            for name in files:
                if (name.endswith('.tex')) or (name.endswith('.ltx')):
                    ret.append(os.path.join(root,name))
        return ret

    # Set a list of input files to use
    if ctx.options.infile:
        sf = []
        sf.append(ctx.options.infile)
        ctx.env.SOURCEFILES = sf
    else :
       ctx.env.SOURCEFILES = find_tex_files(ctx.env.SPELLCK)

    # run aspell
    from os import system
    for f in ctx.env.SOURCEFILES :
        system(ctx.env.ASPELL + ' -c ' + f)
        system('rm ' + f + '.' +'bak')

# Class declarartion to bind the build context to the spellck command
from waflib.Build import BuildContext
class spck(BuildContext):
    cmd='spellck'
    fun='spellck'
