#!/usr/bin/python

import os, shutil, sys


if len(sys.argv) == 1:
    print """
This script is called like so:

     %s  path/to/file.tex  another/path/to/a/file.tex  ....

If path/to/file.tex already exists, nothing happens.
If path/to/file.tex does not exist, it is created (including the directory that contains it),
and if there is a file $HOME/templates/default.tex or $SAGEMATHCLOUD/templates/default.tex (for tex extension),
then that template file is set to the initial contents. """%(sys.argv[0])
    sys.exit(1)

def new_file(path):
    if os.path.exists(path):
        # nothing to do.
        return

    base, filename = os.path.split(path)

    if base and not os.path.exists(base):
        os.makedirs(base)

    ext = os.path.splitext(path)[1]
    for places in [os.environ['HOME'], os.environ['SAGEMATHCLOUD']]:
        template = os.path.join(places, 'templates', 'default' + ext)
        if os.path.exists(template):
            shutil.copyfile(template, path)
            return

    # No template found
    open(path,'w').close()


for x in sys.argv[1:]:
    new_file(x)



