#!/usr/pkg/bin/python2.7
# -*- coding: utf-8 -*-
#
# Copyright 2014  Aurélien Gâteau <agateau@kde.org>
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# 1. Redistributions of source code must retain the above copyright
#    notice, this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright
#    notice, this list of conditions and the following disclaimer in the
#    documentation and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
# OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
# IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
# NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
# THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

# Python 2/3 compatibility (NB: we require at least 2.7)
from __future__ import division, absolute_import, print_function, unicode_literals

import argparse
import os
import logging
import shutil
import subprocess
import sys
import tempfile
import time

from kapidox import utils

DESCRIPTION = """
Generate Graphviz dot files for one or all frameworks.
"""

def generate_dot(fw_dir, fw_name, output_dir):
    """Calls cmake to generate the dot file for a framework.

    Returns true on success, false on failure"""
    dot_path = os.path.join(output_dir, fw_name + ".dot")
    build_dir = tempfile.mkdtemp(prefix="depdiagram-prepare-build-")
    try:
        ret = subprocess.call(["cmake", fw_dir, "--graphviz={}".format(dot_path)],
            stdout=open("/dev/null", "w"),
            cwd=build_dir)
        if ret != 0:
            if os.path.exists(dot_path):
                os.remove(dot_path)
            logging.error("Generating dot file for {} failed.".format(fw_name))
            return False
        # Add a timestamp and version info to help with diagnostics
        with open(dot_path, "a") as f:
            f.write("\n# Generated on {}\n".format(time.ctime()))
            version = utils.get_kapidox_version()
            if version:
                f.write("# By {} {}\n".format(sys.argv[0], version))
    finally:
        shutil.rmtree(build_dir)
    return True


def prepare_one(fw_dir, output_dir):
    fw_name = utils.parse_fancyname(fw_dir)
    if fw_name is None:
        return False

    yaml_path = os.path.join(fw_dir, "metainfo.yaml")
    if not os.path.exists(yaml_path):
        logging.error("'{}' is not a framework: '{}' does not exist.".format(fw_dir, yaml_path))
        return False

    if not os.path.exists(output_dir):
        os.makedirs(output_dir)

    if not generate_dot(fw_dir, fw_name, output_dir):
        return False
    shutil.copyfile(yaml_path, os.path.join(output_dir, fw_name + ".yaml"))
    return True


def prepare_all(fw_base_dir, dot_dir):
    """Generate dot files for all frameworks.

    Looks for frameworks in `fw_base_dir`. Output the dot files in sub dirs of
    `dot_dir`.
    """
    lst = os.listdir(fw_base_dir)
    fails = []
    for idx, fw_name in enumerate(lst):
        fw_dir = os.path.join(fw_base_dir, fw_name)
        if not os.path.isdir(fw_dir):
            continue

        progress = int(100 * (idx + 1) / len(lst))
        print("{}% {}".format(progress, fw_name))
        if not prepare_one(fw_dir, dot_dir):
            fails.append(fw_name)
    return fails


def main():
    parser = argparse.ArgumentParser(description=DESCRIPTION)

    group = parser.add_mutually_exclusive_group(required=True)
    group.add_argument("-s", "--single",
        help="Generate dot files for the framework stored in DIR",
        metavar="DIR")
    group.add_argument("-a", "--all",
        help="Generate dot files for all frameworks whose dir is in BASE_DIR",
        metavar="BASE_DIR")
    parser.add_argument("dot_dir",
        help="Destination dir where dot files will be generated")

    args = parser.parse_args()

    dot_dir = os.path.abspath(args.dot_dir)

    if args.single:
        fw_dir = os.path.abspath(args.single)
        if prepare_one(fw_dir, dot_dir):
            return 0
        else:
            return 1
    else:
        fw_base_dir = os.path.abspath(args.all)
        fails = prepare_all(fw_base_dir, dot_dir)
        if fails:
            logging.error("{} framework(s) failed: {}".format(len(fails), ", ".join(fails)))
            return 1
        else:
            return 0


if __name__ == "__main__":
    sys.exit(main())
