#!/usr/bin/env python3
import os
import sys
from subprocess import run
from shutil import copyfile
from os.path import splitext, join


def make_tex(infilename):
    outfilename = splitext(infilename)[0]+'.tex'
    run(('pandoc', '--biblatex',
         '-F', 'pandoc-crossref',
         '-F', '../filters/note_filter.py',
         '-s', infilename, '-o', outfilename,
         '--metadata=bibliography:references.bib',
         '--template=chapter',
         ))
    with open(outfilename, 'r') as f:
        body = f.read()
        body = body.replace(r'\printbibliography', '')
    with open(outfilename, 'w') as f:
        f.write(body)


def make_html(infilename):
    outfilename = splitext(infilename)[0]+'.html'
    run(('pandoc',
         '-F', 'pandoc-crossref',
         '-F', 'pandoc-citeproc',
         '-s', infilename, '-o', outfilename,
         '--mathjax',
         '--metadata=linkReferences:true',
         '--metadata=bibliography:references.bib',
         '--metadata=citation-style:american-institute-of-physics.csl',
         '--template=chapter',
         ))


def main(src, dest_fmt):
    print(f'Converting {src} to {dest_fmt}...', end='', flush=True)

    copyfile(join('content', src), join('build', src))
    os.chdir('build')
    if dest_fmt == 'html':
        make_html(src)
    else:
        make_tex(src)
    print('Done')


if __name__ == '__main__':
    if len(sys.argv) < 3 or sys.argv[2] not in ('html', 'tex'):
        print('usage: ./convert.py input_markdown [html|tex]')
        sys.exit(1)
    main(sys.argv[1], sys.argv[2])
