#!/usr/bin/env python3
""" builds documentation files from multimarkdown (mmd) source
    to various formats, including the web site and pdf.
"""

import subprocess
import glob
import os
import sys
import time
import shutil

src = [
    "intro.mmd", 
    "downloads.mmd",
    "quickstart.mmd",
    "faq.mmd",
    "dirstruct.mmd",
    "premake.mmd",
    "legal.mmd",
    "concepts.mmd",
    "concepts3d.mmd",
    "voicemanagement.mmd",
    "examples.mmd",
    "foreign_interface.mmd",
    "c_api.mmd",
    "python_api.mmd",
    "ruby_api.mmd",
    "rpgmaker_api.mmd",
    "bmx_api.mmd",
    "gamemaker_api.mmd",
    "cs_api.mmd",
    "d_api.mmd",
    "codegen.mmd",
    "basics.mmd",
    "attributes.mmd",
    "faders.mmd",
    "voicegroups.mmd", 
    "coremisc.mmd",
    "core3d.mmd",
    "audiosource.mmd",
    "newsoundsources.mmd",
    "wav.mmd",
    "wavstream.mmd",
    "speech.mmd",
    "sfxr.mmd",
    "modplug.mmd",
    "monotone.mmd",
    "tedsid.mmd",
    "vizsn.mmd",
    "vic.mmd",
    "filters.mmd",
    "biquadfilter.mmd",
    "echofilter.mmd",
    "lofifilter.mmd",
    "flangerfilter.mmd",
    "dcremovalfilter.mmd",
    "fftfilter.mmd",
    "bassboostfilter.mmd",
    "waveshaperfilter.mmd",
    "mixbus.mmd",
    "queue.mmd",
    "collider.mmd",
    "attenuator.mmd",
    "file.mmd",
    "backends.mmd"
    ]

website_only = [
    "downloads.mmd"
    ]

unknown = 0
for file in glob.glob("*.mmd"):
    if file not in src:
        unknown = 1
        print(file + " not included in docs!")
        
if unknown:
    print("Add the new files to makedoc.py, soloud.tex and htmlpre.txt.")
    sys.exit()

datestring = time.strftime("%Y%m%d")
if not os.path.exists(datestring + "/web"):
  os.makedirs(datestring + "/web")
if not os.path.exists("temp/"):
  os.makedirs("temp/")
    
print("- -- --- -- - Generating single-file HTML docs")

callp = ["pandoc", "-s", "-t", "html5", "-f", "markdown-smart", "--metadata", 'title="SoLoud ' + datestring + '"',  "-H", "singlehtml_head.txt", "-B", "singlehtml_body.txt", "--toc", "--self-contained", "--default-image-extension=png", "-o", datestring + "/soloud_" + datestring + ".html"]
for x in src:
    if x not in website_only:
        callp.append(x)
subprocess.call(callp)

print("- -- --- -- - Generating web site")
for x in src:
    subprocess.call(["pandoc", "--template=html.pandoc", "-f", "markdown-smart", "--metadata", 'title="SoLoud ' + datestring + ' ' + x[:len(x)-4] + '"', "-B", "htmlpre.txt", "-A", "htmlpost.txt", "--default-image-extension=png", x, "-o", datestring + "/web/" + x[:len(x)-3]+"html.bak"])
    with open(datestring + "/web/" + x[:len(x)-3]+"html", "w") as file_out:
        with open(datestring + "/web/" + x[:len(x)-3]+"html.bak", "r") as file_in:
            for line in file_in:
                file_out.write(line.replace('code>', 'code>\n').replace('::','::<wbr>').replace('\xc2','').replace('\xa0',''))
    if x == "intro.mmd":
        if os.path.isfile(datestring + "/web/index.html"):
            os.remove(datestring + "/web/index.html")
        os.rename(datestring + "/web/intro.html", datestring + "/web/index.html")

print("- -- --- -- - Generating epub")

callp = ["pandoc", "-N", "--toc", "--epub-cover-image=images/cover.png", "-t", "epub3", "--default-image-extension=png", "-f", "markdown-smart", "--css=epub.css", "--epub-metadata=metadata.xml", "-o", datestring + "/soloud_" + datestring + ".epub", "title.txt"]
for x in src:
    if x not in website_only:
        callp.append(x)
subprocess.call(callp)

print("- -- --- -- - Converting epub -> mobi (kindlegen_output.txt)")
with open('kindlegen_output.txt', 'w') as outfile:
    subprocess.call(["kindlegen", datestring + "/soloud_" + datestring + ".epub", "-c2"], stdout=outfile)

print("- -- --- -- - Generating LaTex")

for x in src:
    if x not in website_only:
        subprocess.call(["pandoc", "-t", "latex", "--listings", "--default-image-extension=pdf", "--top-level-division=chapter", x, "-o", "temp/" + x[:len(x)-3]+"tex.orig"])
        with open("temp/" + x[:len(x)-3]+"tex", "w") as file_out:
            with open("temp/" + x[:len(x)-3]+"tex.orig", "r") as file_in:
                for line in file_in:
                    file_out.write(line.replace('\\begin{longtable}[]{@{}ll@{}}', '\\begin{tabulary}{\\textwidth}{lJ}').replace('\\begin{longtable}[]{@{}lll@{}}', '\\begin{tabulary}{\\textwidth}{lJJ}').replace('\\begin{longtable}[]{@{}llll@{}}', '\\begin{tabulary}{\\textwidth}{lJJJ}').replace('\\endhead','').replace('\\end{longtable}','\\end{tabulary}'))

print("- -- --- -- - Generating pdf (xelatex_output.txt)")

with open('xelatex_output.txt', 'w') as outfile:
    subprocess.call(["xelatex", "SoLoud.tex"], stdout=outfile)
    print("- -- --- -- - Generating pdf pass 2..")
    subprocess.call(["xelatex", "SoLoud.tex"], stdout=outfile)

shutil.move("SoLoud.pdf", datestring + "/soloud_" + datestring + ".pdf")

print("- -- --- -- - Cleanup..")
tempsuffix = ["aux", "toc", "out", "log", "lg", "4ct", "4tc", "idv", "tmp", "xdv", "xref", "bak"]
for suffix in tempsuffix:
    for file in glob.glob("*."+suffix):
        os.remove(file)
    for file in glob.glob(datestring + "/web/*."+suffix):
        os.remove(file)
for file in glob.glob("temp/*"):
   os.remove(file)
os.rmdir("temp")

print("- -- --- -- - Done - " + datestring)

[((74, 12, 74, 30), 'glob.glob', 'glob.glob', ({(74, 22, 74, 29): '"""*.mmd"""'}, {}), "('*.mmd')", False, 'import glob\n'), ((83, 13, 83, 36), 'time.strftime', 'time.strftime', ({(83, 27, 83, 35): '"""%Y%m%d"""'}, {}), "('%Y%m%d')", False, 'import time\n'), ((95, 0, 95, 22), 'subprocess.call', 'subprocess.call', ({(95, 16, 95, 21): 'callp'}, {}), '(callp)', False, 'import subprocess\n'), ((115, 0, 115, 22), 'subprocess.call', 'subprocess.call', ({(115, 16, 115, 21): 'callp'}, {}), '(callp)', False, 'import subprocess\n'), ((138, 0, 138, 72), 'shutil.move', 'shutil.move', ({(138, 12, 138, 24): '"""SoLoud.pdf"""', (138, 26, 138, 71): "(datestring + '/soloud_' + datestring + '.pdf')"}, {}), "('SoLoud.pdf', datestring + '/soloud_' + datestring + '.pdf')", False, 'import shutil\n'), ((147, 12, 147, 31), 'glob.glob', 'glob.glob', ({(147, 22, 147, 30): '"""temp/*"""'}, {}), "('temp/*')", False, 'import glob\n'), ((149, 0, 149, 16), 'os.rmdir', 'os.rmdir', ({(149, 9, 149, 15): '"""temp"""'}, {}), "('temp')", False, 'import os\n'), ((81, 4, 81, 14), 'sys.exit', 'sys.exit', ({}, {}), '()', False, 'import sys\n'), ((84, 7, 84, 42), 'os.path.exists', 'os.path.exists', ({(84, 22, 84, 41): "(datestring + '/web')"}, {}), "(datestring + '/web')", False, 'import os\n'), ((85, 2, 85, 34), 'os.makedirs', 'os.makedirs', ({(85, 14, 85, 33): "(datestring + '/web')"}, {}), "(datestring + '/web')", False, 'import os\n'), ((86, 7, 86, 30), 'os.path.exists', 'os.path.exists', ({(86, 22, 86, 29): '"""temp/"""'}, {}), "('temp/')", False, 'import os\n'), ((87, 2, 87, 22), 'os.makedirs', 'os.makedirs', ({(87, 14, 87, 21): '"""temp/"""'}, {}), "('temp/')", False, 'import os\n'), ((119, 4, 119, 105), 'subprocess.call', 'subprocess.call', (), '', False, 'import subprocess\n'), ((134, 4, 134, 62), 'subprocess.call', 'subprocess.call', (), '', False, 'import subprocess\n'), ((136, 4, 136, 62), 'subprocess.call', 'subprocess.call', (), '', False, 'import subprocess\n'), ((143, 16, 143, 38), 'glob.glob', 'glob.glob', ({(143, 26, 143, 37): "('*.' + suffix)"}, {}), "('*.' + suffix)", False, 'import glob\n'), ((145, 16, 145, 56), 'glob.glob', 'glob.glob', ({(145, 26, 145, 55): "(datestring + '/web/*.' + suffix)"}, {}), "(datestring + '/web/*.' + suffix)", False, 'import glob\n'), ((148, 3, 148, 18), 'os.remove', 'os.remove', ({(148, 13, 148, 17): 'file'}, {}), '(file)', False, 'import os\n'), ((105, 11, 105, 57), 'os.path.isfile', 'os.path.isfile', ({(105, 26, 105, 56): "(datestring + '/web/index.html')"}, {}), "(datestring + '/web/index.html')", False, 'import os\n'), ((107, 8, 107, 81), 'os.rename', 'os.rename', ({(107, 18, 107, 48): "(datestring + '/web/intro.html')", (107, 50, 107, 80): "(datestring + '/web/index.html')"}, {}), "(datestring + '/web/intro.html', datestring + '/web/index.html')", False, 'import os\n'), ((144, 8, 144, 23), 'os.remove', 'os.remove', ({(144, 18, 144, 22): 'file'}, {}), '(file)', False, 'import os\n'), ((146, 8, 146, 23), 'os.remove', 'os.remove', ({(146, 18, 146, 22): 'file'}, {}), '(file)', False, 'import os\n'), ((106, 12, 106, 53), 'os.remove', 'os.remove', ({(106, 22, 106, 52): "(datestring + '/web/index.html')"}, {}), "(datestring + '/web/index.html')", False, 'import os\n')]