#!/usr/bin/env python3
from argparse import ArgumentParser
from tempfile import mktemp
from subprocess import call
from sys import exit
from os import remove
from os.path import split, splitext


def main(source_file, language, title, output, author):
    with open(source_file) as f:
        source = f.read()
    tmp = mktemp(suffix='.md')
    if output is None:
        output = splitext(split(source_file)[1])[0]+'.pdf'
    with open(tmp, 'w') as f:
        f.write(f'''---
title: {title}
author: {author}
geometry: margin=2cm
---

```{language}
{source}
```
        ''')
    retcode = call(['pandoc', '-o', output, tmp])
    remove(tmp)
    return retcode


if __name__ == '__main__':
    parser = ArgumentParser()
    parser.add_argument('source_file')
    parser.add_argument('-l', '--language', default='python')
    parser.add_argument('-t', '--title', default='')
    parser.add_argument('-o', '--output', default=None)
    parser.add_argument('-a', '--author', default='')

    args = parser.parse_args()
    exit(main(args.source_file, args.language, args.title, args.output, args.author))
