#!/bin/bash

DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null && pwd )"
source "${DIR}/standard.lib"

# Assume all test passed
exitcode=0

# Import local standard config file
if [ -f "standard.config" ]; then
    set -a
    source standard.config
    set +a
else
    echo "Could not find 'standard.config' file.", please make a 'standard.config' by following document.
    exit 1
fi


########## PARAM DETECTOR ##########
if [ ! -z "$1" ]; then
    PHPCPD_ENABLED=false
    PHPMD_ENABLED=false
    PHPCS_ENABLED=false
    PHPUNIT_ENABLED=false

    PARAM="$1"
    PARAM=$( echo "$PARAM"|tr '/a-z/' '/A-Z/')
    eval "$PARAM"_ENABLED=true
fi


resolve_paths ${PATHS}

if [ ${#checks[@]} -lt 1 ]; then
    echo "Paths specfiied in configuration file are invalid or could not be found"
    echo "PATHS=<path>,<path>,..."
    exit 1
fi

# Combine directories into a single variable
checks=${checks[@]}

# Run phpcpd
if ${PHPCPD_ENABLED}; then
    resolve_executable phpcpd

    if [ ${?} -eq 0 ]; then
        echo "Running php copy/paste detector..."
        results ${executable} --ansi --min-lines=${PHPCPD_MIN_LINES} --min-tokens=${PHPCPD_MIN_TOKENS} ${checks}
    fi
fi

# Run phpmd
if ${PHPMD_ENABLED}; then
    resolve_executable phpmd

    if [ ${?} -eq 0 ]; then
        echo "Running php mess detector..."
        if [ -f phpmd.xml ]; then
            results ${executable} ${checks// /,} text phpmd.xml
        else
            results ${executable} ${checks// /,} text ${PHPMD_RULESETS}
        fi
    fi
fi

# Run phpcs
if ${PHPCS_ENABLED}; then
    resolve_executable phpcs

    if [ ${?} -eq 0 ]; then
        show_sniff_arg=$([ "$PHPCS_SHOW_SNIFF_NAME" = true ] && echo '-s')
        echo "Running php code sniffer..."
        if [ -f phpcs.xml ]; then
            results ${executable} --colors ${checks} ${show_sniff_arg}
        else
            results ${executable} --standard=${PHPCS_STANDARDS} --colors --report=full ${checks} ${show_sniff_arg}
        fi
    fi
fi

# Run phpunit
if ${PHPUNIT_ENABLED}; then
    echo "Running phpunit..."
    # Make sure this can run
    if [ ! -f phpunit.xml ] && ([ ! -f vendor/autoload.php ] || [ ! -d ${PHPUNIT_TEST_DIRECTORY} ]); then
        echo "ERROR: Can't run phpunit as phpunit.xml can't be loaded and vendor/autoload.php or tests directory is missing"
    else
        # Prefer paratest
        resolve_executable paratest

        if [ ${?} -eq 0 ]; then
            if [ -f phpunit.xml ]; then
                phpunit_command="${executable} -p8 --runner=WrapperRunner --colors"
            else
                phpunit_command="${executable} -p8 --runner=WrapperRunner --bootstrap=vendor/autoload.php --colors ${PHPUNIT_TEST_DIRECTORY}"
            fi
        else
            resolve_executable phpunit

            if [ ${?} -eq 0 ]; then
                if [ -f phpunit.xml ]; then
                    phpunit_command="${executable} --colors=always"
                else
                    phpunit_command="${executable} --bootstrap vendor/autoload.php --colors=always ${PHPUNIT_TEST_DIRECTORY}"
                fi
            fi
        fi

        if [ ! -z ${phpunit_command+xxx} ]; then
            # If coverage is enabled, add it
            if ${PHPUNIT_ENABLE_CODE_COVERAGE}; then
                # Prefer running with phpdbg
                if [ ! -z $(which phpdbg) ]; then
                    phpunit_command="$(command -v phpdbg) -qrr ${phpunit_command#php } --coverage-text"
                else
                    phpunit_command="${phpunit_command} --coverage-text"
                fi

                # If junit is enabled, add it
                if [ ! -z ${PHPUNIT_JUNIT_LOG_PATH} ]; then
                    phpunit_command="${phpunit_command} --log-junit=${PHPUNIT_JUNIT_LOG_PATH}"
                fi
            fi

            # Run and capture result
            echo ${phpunit_command}
            results=$(${phpunit_command})
            if [ ${?} -ne 0 ]; then
                exitcode=1
                echo -e "\n${results}\n"
            fi

            # Check coverage if applicable
            if ${PHPUNIT_ENABLE_CODE_COVERAGE}; then
                phpunit_line_coverage=$(echo "${results}" | grep -i 'lines:' | head -1 | perl -ne 'print ${1} if /([\.\d]+(?=%))/')

                # If coverage didn't run, warn but don't fail, otherwise compare it
                if [ -z ${phpunit_line_coverage} ]; then
                    echo -e "\033[43;5;30mWARNING: Code coverage not checked, xdebug may not be installed\033[49;5;39m"
                else
                    if [ $(echo "${phpunit_line_coverage} < ${PHPUNIT_COVERAGE_MINIMUM_LEVEL}" | bc -l) -eq 1 ]; then
                        exitcode=1
                        echo -e "\n${results}\n"
                        echo -e "Minimum code coverage level not met, expected ${PHPUNIT_COVERAGE_MINIMUM_LEVEL}% got ${phpunit_line_coverage}%"
                    fi
                fi
            fi
        fi
    fi
fi

if [ ${exitcode} -eq 0 ]; then
    echo -e "\033[1;92m"
    echo "It all looks good!"
else
    echo -e "\033[1;91m"
    echo -e "Please fix errors!"
fi

printf "\033[m\n"

# If there was an error exit with error code
exit ${exitcode}