# Copyright 2013 Daniel Narvaez
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import os
import subprocess
import json

from osbuild import config
from osbuild import command
from osbuild import xvfb
from osbuild import build

_checkers = {}


def check_one(module_name):
    for module in config.load_modules():
        if module.name == module_name:
            return _check_module(module)

    return False


def check():
    if not build.build():
        return False

    modules = config.load_modules()
    for module in modules:
        if not _check_module(module):
            return False

    return True


def _check_module(module):
    build_system = module.get_build_system()

    if build_system and module.has_checks:
        print("* Checking %s" % module.name)
        return _checkers[build_system](module)

    return True


def _volo_checker(module):
    source_dir = module.get_source_dir()

    os.chdir(source_dir)
    with open("package.json") as f:
        package = json.load(f)
        if "dependencies" in package["volo"]:
            command.run(["volo", "-f", "add"])

    test_dir = os.path.join(source_dir, "test")
    if os.path.exists(test_dir):
        os.chdir(test_dir)
        subprocess.check_call(["karma", "start", "--single-run"])

    for root, dirs, files in os.walk(module.get_source_dir()):
        if root == source_dir and "lib" in dirs:
            dirs.remove("lib")
        for f in files:
            if f.endswith(".js"):
                try:
                    command.run(["jshint", os.path.join(root, f)])
                except subprocess.CalledProcessError:
                    return False
    return True

_checkers['volo'] = _volo_checker


def _distutils_checker(module):
    result = True

    os.chdir(module.get_source_dir())

    command.run(["python", "setup.py", "lint"])

    xvfb_proc, orig_display = xvfb.start()

    try:
        command.run(["python", "setup.py", "test"])
    except subprocess.CalledProcessError:
        result = False

    xvfb.stop(xvfb_proc, orig_display)

    return result

_checkers['distutils'] = _distutils_checker


def _autotools_checker(module):
    result = True
    os.chdir(module.get_source_dir())
    xvfb_proc, orig_display = xvfb.start()

    try:
        command.run(["dbus-launch", "--exit-with-session",
                     "make", "check"])
    except subprocess.CalledProcessError:
        result = False

    xvfb.stop(xvfb_proc, orig_display)

    return result

_checkers['autotools'] = _autotools_checker

@@ -612,16 +612,76 @@
 ort json
+%0Aimport logging%0Aimport difflib%0Afrom StringIO import StringIO
 %0A%0Afrom o
@@ -1396,24 +1396,324 @@
 turn True%0A%0A%0A
+def _diff_output(output, path):%0A    result = False%0A%0A    with open(path) as f:%0A        diff = difflib.unified_diff(f.readlines(),%0A                                    StringIO(output).readlines())%0A        for line in diff:%0A            logging.error(line)%0A            result = True%0A%0A    return result%0A%0A%0A
 def _volo_ch
@@ -2293,24 +2293,66 @@
 f in files:%0A
+            path = os.path.join(root, f)%0A%0A
             
@@ -2373,16 +2373,17 @@
 %22.js%22):%0A
+%0A
         
@@ -2442,84 +2442,925 @@
 t%22, 
-os.path.join(root, f)%5D)%0A                except subprocess.CalledProcessError
+path%5D)%0A                except subprocess.CalledProcessError:%0A                    return False%0A%0A                logging.info(%22Running js-beautify on %25s%22 %25 path)%0A                args = %5B%22js-beautify%22, %22--good-stuff%22, path%5D%0A                if _diff_output(subprocess.check_output(args), path):%0A                    return False%0A            elif f.endswith(%22.css%22):%0A                logging.info(%22Running js-beautify on %25s%22 %25 path)%0A                args = %5B%22js-beautify%22, %22--type%22, %22css%22,%0A                        %22--indent-size%22, %222%22, path%5D%0A                if _diff_output(subprocess.check_output(args), path):%0A                    return False%0A            elif f.endswith(%22.html%22):%0A                logging.info(%22Running js-beautify on %25s%22 %25 path)%0A                args = %5B%22js-beautify%22, %22--type%22, %22html%22,%0A                        %22--indent-size%22, %222%22, path%5D%0A                if _diff_output(subprocess.check_output(args), path)
 :%0A  
@@ -3386,24 +3386,25 @@
 eturn False%0A
+%0A
     return T

Add js-beautify check