#! /usr/bin/env python3
"""Writes an org-mode file and setup file as well as a Makefile to create
html and pdf output as well as other formats."""
###############################################################################
from sys import argv
from os import makedirs, chmod
from optparse import OptionParser

###############################################################################
from orgtexts import orgtexts

###############################################################################
version = "131:1e68e59c25fd"
###############################################################################
t = orgtexts()
USAGE = t["usage"]
###############################################################################
p = OptionParser()
###############################################################################
p.add_option(
    "-u",
    "--usage",
    action="store_true",
    help="print usage message and exit",
    dest="usage",
)
###############################################################################
p.add_option(
    "-v",
    "--version",
    action="store_true",
    help="print version number and exit",
    dest="version",
)
###############################################################################
(o, a) = p.parse_args()
if o.usage:
    print("-" * 72 + USAGE + "-" * 72)
    exit()
###############################################################################
if o.version:
    print(version)
    exit()
###############################################################################
if len(argv) != 3:
    print(USAGE)
    exit()
###############################################################################
(DN, FN) = (argv[1], argv[2])


###############################################################################
def orgnote(dn, fn):
    makedirs(dn, exist_ok=True)
    tmp = dn + "/" + ".tmp"
    makedirs(tmp, exist_ok=True)
    ###########################################################################
    s = t["setup"]
    ###########################################################################
    with open(dn + "/" + ".tmp/" + fn + ".setup", "w") as setup_file:
        setup_file.write(s)
    ###########################################################################
    with open(dn + "/" + fn + ".org", "w") as org_file:
        org_file.write(r"#+SETUPFILE: " + ".tmp/" + fn + ".setup\n")
        org_file.write(r"* Heading")
    ###########################################################################
    with open(tmp + "/" + fn + ".h1html", "w") as header_1:
        header_1.write(t["htmlhead1"])
    ###########################################################################
    with open(tmp + "/" + fn + ".h2html", "w") as header_2:
        header_2.write(t["htmlhead2"] + "\n")
    ###########################################################################
    with open(tmp + "/" + fn + ".fhtml", "w") as footer:
        footer.write(t["htmlfoot"])
    ###########################################################################
    with open(tmp + "/" + "template.latex", "w") as template:
        template.write(t["latextemplate"])
    ###########################################################################
    with open(tmp + "/" + "sample.org", "w") as sample:
        sample.write(t["sample"])
    ###########################################################################
    with open(dn + "/Makefile", "w") as mf:
        mf.write("help:\n\t")
        mf.write("@grep -E '^[a-zA-Z_-]+:.*?## .*$$' $(MAKEFILE_LIST)")
        mf.write("| awk 'BEGIN {FS = ")
        mf.write('":.*?## "};')
        mf.write('{printf "\\033[31m%-16s\\033[32m %s\\n", $$1, $$2}')
        mf.write("'")
        mf.write("\n")
        mf.write(".PHONY: help")
        mf.write("\n\n")
        #######################################################################
        mf.write("all: ")
        mf.write("html text ascii md asciidoc adochtml odt docx pdf lwarphtml")
        mf.write("## generate all formats")
        mf.write("\n")
        mf.write(".PHONY:")
        mf.write("\n\n")
        #######################################################################
        mf.write("html: ## generate html \n\t")
        mf.write("head -n2 " + fn + ".org" + " | tail -n1 | cut -c 3- ")
        mf.write("> .tmp/TITLE \n\t")
        mf.write("pandoc -f org+smart -t html -o .tmp/" + fn + ".phtml")
        mf.write(" " + fn + ".org \n\t")
        mf.write("sed -i 's/\“/\&ldquo;/g' " + ".tmp/" + fn + ".phtml\n\t")
        mf.write("sed -i 's/\”/\&rdquo;/g' " + ".tmp/" + fn + ".phtml\n\t")
        mf.write("sed -i 's/\‘/\&lsquo;/g' " + ".tmp/" + fn + ".phtml\n\t")
        mf.write("sed -i 's/\’/\&rsquo;/g' " + ".tmp/" + fn + ".phtml\n\t")
        mf.write("cat .tmp/" + fn + ".h1html" + " " + ".tmp/TITLE" + " ")
        mf.write(".tmp/" + fn + ".h2html" + " " + ".tmp/" + fn + ".phtml")
        mf.write(" " + ".tmp/" + fn + ".fhtml > " + fn + ".html\n\t")
        mf.write("mkdir -p htmlout\n\t")
        mf.write("mv" + " " + fn + ".html" + " " + "htmlout")
        mf.write("\n\n")
        #######################################################################
        mf.write("text: ## generate utf-8 text \n\t")
        mf.write("emacs --batch " + fn + ".org" + " \\" + "\n")
        mf.write("        " + "--eval" + " ")
        mf.write('"(org-ascii-export-as-ascii')
        mf.write(" nil nil nil nil ")
        mf.write("'(:ascii-charset utf-8))'")
        mf.write('"')
        mf.write(" " + "\\" + "\n")
        mf.write("        ")
        mf.write("--eval ")
        mf.write('"(write-file \\"' + fn + ".text\\" + '")' + '" --kill')
        mf.write("\n\n")
        #######################################################################
        mf.write("ascii: ## generate ascii text\n\t")
        mf.write("emacs --batch" + " " + fn + ".org")
        mf.write(" " + "-f org-ascii-export-to-ascii")
        mf.write("\n\n")
        #######################################################################
        mf.write("md: ## generate markdown\n\t")
        mf.write("emacs --batch" + " " + fn + ".org")
        mf.write(" " + "-f org-md-export-to-markdown")
        mf.write("\n\n")
        #######################################################################
        mf.write("asciidoc: ## generate asciidoc\n\t")
        mf.write("pandoc -f org -t asciidoc" + " " + fn + ".org" + " ")
        mf.write("-o" + " " + fn + ".adoc")
        mf.write("\n\n")
        #######################################################################
        mf.write("adochtml: asciidoc ## html via asciidoc\n\t")
        mf.write("asciidoc" + " " + "-o" + " " + fn + ".adoc.html")
        mf.write(" " + fn + ".adoc")
        mf.write("\n\n")
        #######################################################################
        mf.write("odt: ## generate odt (LibreOffice format)\n\t")
        mf.write("emacs --batch")
        mf.write(" " + fn + ".org" + " -f org-odt-export-to-odt")
        mf.write("\n\n")
        #######################################################################
        mf.write("docx: odt ")
        mf.write("## generate docx (Microsoft Word format) via odt\n\t")
        mf.write("pandoc -f odt -t docx")
        mf.write(" " + fn + ".odt" + " " + "-o " + fn + ".docx")
        mf.write("\n\n")
        #######################################################################
        mf.write("pdf: ## generate pdf via LaTeX\n\t")
        mf.write("pandoc -f org+smart -t latex --template")
        mf.write(" " + ".tmp/template.latex" + " ")
        mf.write(fn + ".org" + " " + "-o " + fn + ".tex\n\t")
        mf.write("lualatex" + " " + fn + ".tex\n\t")
        mf.write("mkdir -p .orgnotelogs\n\t")
        mf.write("mv *.log *.out *.aux .orgnotelogs/\n\t")
        mf.write("mkdir -p out\n\t")
        mf.write("mv " + fn + ".pdf out")
        mf.write("\n\n")
        #######################################################################
        mf.write("lwarphtml: ## generate html via LaTeX and lwapr\n\t")
        mf.write("pandoc -f org+smart -t latex --template")
        mf.write(" " + ".tmp/template.latex" + " ")
        mf.write(fn + ".org" + " " + "-o " + fn + ".tex\n\t")
        mf.write("lualatex" + " " + fn + ".tex\n\t")
        mf.write("lwarpmk html\n\t")
        mf.write("mkdir -p .orgnotelogs\n\t")
        mf.write("mkdir -p out\n\t")
        mf.write(
            "mv"
            + " "
            + fn
            + ".pdf"
            + " "
            + fn
            + ".html"
            + " "
            + "lwarp.css"
            + " "
            + "out\n\t"
        )
        mf.write("mv *.log *.out *.aux .orgnotelogs/")
        mf.write("\n\n")
        #######################################################################
        mf.write("sample: ## replace current .org file with sample text\n\t")
        mf.write("cp" + " " + fn + ".org" + " " + fn + ".org.samplebak\n\t")
        mf.write("cp .tmp/sample.org" + " " + fn + ".org\n\t")
        mf.write("sed -i s/sample.setup/" + fn + ".setup/g " + fn + ".org")
        mf.write("\n\n")
        #######################################################################
        mf.write("clean: ## remove generated .tex file and logs\n\t")
        mf.write("rm -f " + fn + ".tex " + "*~ " + ".logs/*\n\t")
        mf.write(
            "rm -f lwarpmk.conf *.ist *.lwarpmkconf *~ *.css *.txt *.xdy comment_* *_html.* *.aux\n\t"
        )
        mf.write("rm -f comment*cut *.txt *.html *.pdf")
        mf.write("\n\n")
        #######################################################################
        exts = [
            ".html",
            ".pdf",
            ".tex",
            ".txt",
            ".text",
            ".md",
            ".adoc",
            ".adoc.html",
            ".odt",
            ".docx",
            ".adoc",
            "*~",
            ".conf",
            ".ist",
            ".xdy",
            ".cut",
            ".css",
        ]
        mf.write("veryclean: ## remove all generated files\n\t")
        mf.write("rm -rf out htmlout\n\t")
        mf.write("rm -f" + " ")
        for e in exts:
            mf.write(fn + e + " ")
        mf.write(".orgnotelogs/*" + "\n")
    ###########################################################################


###############################################################################
orgnote(DN, FN)
###############################################################################
