#!/usr/bin/env python
#
# A tool to quickly initialize a latex "project" based on an x3-template
#
import os
import sys

content = '''
\\input{{document-info}}
%%% Body below this line



%%% Body above this line
\\input{{#{template}-end}}
\\end{{document}}'''

documentinfo_tex = '''
\\input{{#{template}-preamble}}

%
% Begin: Author and Document Information
%
\\def\\documentAuthor{{}}
\\def\\documentTitle{{}}
%
% End: Author and Document Information
%

\\input\{{{template}-begin\}}
'''

makefile = '''
all: document.pdf

document.pdf: *.tex
	latexmk document.tex

clean:
	rm ./*.{{aux,log}}'''

def usage():
    print("usage: ltx template-name init-path")
    sys.exit(1)

def main(templ, path):
    files = ["document.tex", "document-info.tex", "Makefile"]
    templates = [content, documentinfo_tex, makefile]
    if os.path.exists(path):
        if not os.path.isdir(path):
            print("path '{}' exists but is not a directory".format(path))
            sys.exit(1)
    else:
        os.makedirs(path)
    for fn, stmpl in zip(files, templates):
        with open(os.path.join(path, fn), 'w') as f:
            f.write(stmpl.format(template=templ))

if __name__ == "__main__":
    if len(sys.argv) < 3:
        usage()
    main(sys.argv[1], sys.argv[2])
