#!/usr/bin/env python

"""
Botan doc generation script

(C) 2014,2015,2017 Jack Lloyd

Botan is released under the Simplified BSD License (see license.txt)
"""

import sys
import optparse # pylint: disable=deprecated-module
import subprocess
import shutil
import logging
import json
import tempfile
import os
import stat

def get_concurrency():
    """
    Get default concurrency level of build
    """
    def_concurrency = 2

    try:
        import multiprocessing
        return max(def_concurrency, multiprocessing.cpu_count())
    except ImportError:
        return def_concurrency

def have_prog(prog):
    """
    Check if some named program exists in the path
    """
    for path in os.environ['PATH'].split(os.pathsep):
        exe_file = os.path.join(path, prog)
        if os.path.exists(exe_file) and os.access(exe_file, os.X_OK):
            return True
    return False

def find_rst2man():
    possible_names = ['rst2man', 'rst2man.py']

    for name in possible_names:
        if have_prog(name):
            return name
    raise Exception("Was configured with rst2man but could not be located in PATH")

def touch(fname):
    try:
        os.utime(fname, None)
    except OSError:
        open(fname, 'a').close()

def copy_files(src_path, dest_dir):

    logging.debug("Copying %s to %s", src_path, dest_dir)

    file_mode = os.stat(src_path).st_mode

    try:
        os.mkdir(dest_dir)
    except OSError:
        pass

    if stat.S_ISREG(file_mode):
        logging.debug("Copying file %s to %s", src_path, dest_dir)
        shutil.copy(src_path, dest_dir)
    else:
        for f in os.listdir(src_path):
            src_file = os.path.join(src_path, f)
            file_mode = os.stat(src_file).st_mode
            if stat.S_ISREG(file_mode):
                dest_file = os.path.join(dest_dir, f)
                shutil.copyfile(src_file, dest_file)
            elif stat.S_ISDIR(file_mode):
                copy_files(os.path.join(src_path, f), os.path.join(dest_dir, f))

def run_and_check(cmd_line, cwd=None):

    logging.info("Starting %s", ' '.join(cmd_line))

    try:
        proc = subprocess.Popen(cmd_line, cwd=cwd)

        proc.communicate()
    except OSError as e:
        logging.error("Executing %s failed (%s)", ' '.join(cmd_line), e)

    if proc.returncode != 0:
        logging.error("Error running %s", ' '.join(cmd_line))
        sys.exit(1)


def parse_options(args):
    parser = optparse.OptionParser()

    parser.add_option('--verbose', action='store_true', default=False,
                      help='Show debug messages')
    parser.add_option('--quiet', action='store_true', default=False,
                      help='Show only warnings and errors')

    parser.add_option('--build-dir', metavar='DIR', default='build',
                      help='Location of build output (default \'%default\')')
    parser.add_option('--dry-run', default=False, action='store_true',