#!/usr/bin/python3

from jinja2 import Environment, FileSystemLoader
import os
import stat
import shutil

TEMPLATE_PATH = "templates"
PUBLIC_PATH = "/var/www/reudnetz.org/"

files = os.path.join(PUBLIC_PATH, "files")
style = os.path.join(PUBLIC_PATH, "style")



if not os.path.exists(TEMPLATE_PATH):
    os.mkdirs(TEMPLATE_PATH)

if not os.path.exists(PUBLIC_PATH):
    os.makedirs(PUBLIC_PATH)

os.chdir(os.path.dirname(os.path.abspath(__file__)))

env = Environment(loader=FileSystemLoader(TEMPLATE_PATH))

for template in filter(lambda x : x.endswith(".html"), env.list_templates()):
    rendered = env.get_template(template).render(name=template).encode('utf-8')
    output_file = os.path.join(PUBLIC_PATH, template)
    if os.path.exists(output_file):
        os.chmod(output_file, stat.S_IRUSR | stat.S_IWUSR | stat.S_IRGRP | stat.S_IROTH)
    with open(os.path.join(PUBLIC_PATH, template), 'wb') as outfile:
        outfile.write(rendered)
    os.chmod(output_file, stat.S_IRUSR | stat.S_IRGRP | stat.S_IROTH)

if not os.path.exists(files):
    os.makedirs(files)

for filename in os.listdir("files"):
    output_file = os.path.join(files, filename)
    if os.path.exists(output_file):
        os.chmod(output_file, stat.S_IRUSR | stat.S_IWUSR | stat.S_IRGRP | stat.S_IROTH)
    shutil.copy(os.path.join("files", filename), output_file)
    os.chmod(output_file, stat.S_IRUSR | stat.S_IRGRP | stat.S_IROTH)

if not os.path.exists(style):
    os.makedirs(style)

for filename in os.listdir("style"):
    output_file = os.path.join(style, filename)
    if os.path.exists(output_file):
        os.chmod(output_file, stat.S_IRUSR | stat.S_IWUSR | stat.S_IRGRP | stat.S_IROTH)
    shutil.copy(os.path.join("style", filename), output_file)
    os.chmod(output_file, stat.S_IRUSR | stat.S_IRGRP | stat.S_IROTH)
