#!/usr/bin/env python

import pathlib
import subprocess

import yaml

import ninja_syntax


def _nth(n):
    return f"$$(echo $in | cut -d' ' -f{n})"


def _render_rule(w: ninja_syntax.Writer, name, link):
    w.rule(
        f"render_{name}",
        " ".join(
            [
                "./render.py",
                "-stylesheet",
                "gen/main.css",
                "-template",
                _nth(1),
                "-sitemap",
                "sitemap.yaml",
                "-link",
                link,
                "-content",
                _nth(2) + "| minhtml > $out",
            ]
        ),
    )
    return f"render_{name}"


def _render_rss_rule(w: ninja_syntax.Writer):
    w.rule(f"render_rss", " ".join(["./render.py", "-rss", "> $out"]))
    return f"render_rss"


def _compile_sm(w: ninja_syntax.Writer, entries: list, path: pathlib.Path):
    entries = list(
        filter(lambda entry: "enabled" not in entry or entry["enabled"], entries)
    )
    for entry in entries:
        next_path = path.joinpath(entry["name"])
        if "others" in entry and entry["others"]:  # its a dir
            w.build(str(next_path), "mkdir")
            _compile_sm(w, entry["others"], next_path)
        else:
            source = list(next_path.glob("README.md"))
            if len(source) == 1:
                source = str(source[0])
                link = source.replace("content/", "", 1)
                link = source.replace("/README.md", "", 1)
                target = source.replace("content/", "", 1)
                target_dir = target.replace("/README.md", "", 1)
                w.build(target_dir, "mkdir")
                target = target.replace("README.md", "index.html", 1)
                target = "gen/" + target
                cmd = _render_rule(w, source.replace("/", "_", -1), link)
                w.build(
                    target,
                    cmd,
                    inputs=["index.html.jinja", source, "sitemap.yaml", "render.py"],
                )


if __name__ == "__main__":
    with open("sitemap.yaml", "r") as fp:
        sitemap = yaml.safe_load(fp.read())
    with open("build.ninja", "w") as fp:
        w = ninja_syntax.Writer(fp)
        w.comment("automatically generated, do not edit.")
        w.variable("sass_flags", "--style compressed")
        w.rule("mkdir", command="mkdir -p $out")
        w.rule("compile_sass", command="sassc $sass_flags $in $out")
        w.rule("make_qr_code", command="cat $in | qrencode -o $out")
        w.rule("copy", command="cp $in $out")
        w.build("index.html.jinja", "phony")
        w.build("render.py", "phony")
        w.build("sitemap.yaml", "phony")
        w.build("gen", "mkdir")
        w.build("gen/contact.png", "make_qr_code", inputs=["contact.txt"])
        w.build("gen/ks_stylized.png", "copy", inputs=["assets/ks_stylized.png"])
        w.build("gen/favicon.ico", "copy", inputs=["assets/favicon.ico"])
        w.build("gen/style.xsl", "copy", inputs=["assets/style.xsl"])
        w.build("gen/main.css", "compile_sass", inputs=["main.scss"])
        cmd = _render_rule(w, "index", "/")
        w.build(
            "gen/index.html",
            cmd,
            inputs=[
                "index.html.jinja",
                "content/index.md",
                "sitemap.yaml",
                "render.py",
            ],
        )
        cmd = _render_rss_rule(w)
        w.build("gen/index.xml", cmd)
        if sitemap["enabled"]:
            _compile_sm(w, sitemap["entries"], pathlib.Path("./content"))
        w.close()

    subprocess.call(args=["ninja"])