#! /usr/bin/env python

import argparse
import shutil
import subprocess
import sys
import os

from oclintscripts import cmake
from oclintscripts import environment
from oclintscripts import path
from oclintscripts import process

OCLINT_MODULES = ['core', 'metrics', 'rules', 'reporters', 'driver']

arg_parser = argparse.ArgumentParser()
arg_parser.add_argument('module_name', nargs='?', choices=['all'] + OCLINT_MODULES, default='all')
arg_parser.add_argument('-docgen', '--docgen', action='store_true')
arg_parser.add_argument('-release', '--release', action="store_true")
arg_parser.add_argument('-clean', '--clean', action="store_true")
arg_parser.add_argument('-j', type=int, default=0)
arg_parser.add_argument('-llvm-root', '--llvm-root', default=path.build.clang_install_dir)
arg_parser.add_argument('-use-system-compiler', '--use-system-compiler', action="store_true", default=environment.is_linux())
arg_parser.add_argument('-no-ninja', '--no-ninja', action='store_true')
args = arg_parser.parse_args()

def clean_module(module_name):
    build_path = path.oclint_module_build_dir(module_name)
    path.rm_f(build_path)

def build_command(module_name, llvm_root, is_release, no_ninja, is_docgen, module_extras, source_path):
    cmd_build = cmake.builder(source_path)
    if not no_ninja:
        cmd_build.use_ninja()
    if is_release:
        cmd_build.release_build()
    if is_docgen:
        cmd_build.doc_gen_build()
    if environment.is_unix() and not args.use_system_compiler:
        cmd_build.use_local_clang_compiler(llvm_root)
    extras = {'LLVM_ROOT': llvm_root}
    extras.update(module_extras)
    return cmd_build.append_dict(extras).str()

def build_module(module_name, llvm_root, is_release, no_ninja, is_docgen, j):
    build_path = path.oclint_module_build_dir(module_name)
    source_path = path.oclint_module_source_dir(module_name)

    module_extras = {}
    if module_name == "rules" or module_name == "reporters" or module_name == "driver":
        module_extras['OCLINT_SOURCE_DIR'] = path.source.core_dir
        module_extras['OCLINT_BUILD_DIR'] = path.build.core_build_dir
    if module_name == "rules":
        module_extras['OCLINT_METRICS_SOURCE_DIR'] = path.source.metrics_dir
        module_extras['OCLINT_METRICS_BUILD_DIR'] = path.build.metrics_build_dir

    command = build_command(module_name, llvm_root, is_release, no_ninja, is_docgen, module_extras, source_path)

    current_dir = os.getcwd()
    path.mkdir_p(build_path)
    path.cd(build_path)
    process.call(command)
    if no_ninja:
        process.make(j)
    else:
        process.ninja(j)
    path.cd(current_dir)

build_modules = []
if args.module_name == 'all':
    build_modules.extend(OCLINT_MODULES)
else:
    build_modules.append(args.module_name)

if args.clean:
    for module in build_modules:
        clean_module(module)

for module in build_modules:
    build_module(module, args.llvm_root, args.release, args.no_ninja, args.docgen, args.j)
