#!/usr/bin/env python
#coding: utf-8

from mkdocs.build import build
from mkdocs.config import load_config
from mkdocs.serve import serve
import shutil
import sys


def arg_to_option(arg):
    """
    Convert command line arguments into two-tuples of config key/value pairs.
    """
    arg = arg.lstrip('--').replace('-', '_')
    if '=' in arg:
        return arg.split('=', 1)
    return (arg, True)


def main(cmd, options=None):
    """
    Build the documentation, and optionally start the devserver.
    """
    if cmd == 'serve':
        config = load_config(options=options)
        serve(config, options=options)
    elif cmd == 'build':
        config = load_config(options=options)
        build(config)
    else:
        print 'mkdocs [build|serve] {options}'


if __name__ == '__main__':
    cmd = sys.argv[1] if len(sys.argv) >= 2 else None
    args = [arg_to_option(arg) for arg in sys.argv[2:] if arg.startswith('--')]
    main(cmd, options=dict(args))
