#!/usr/bin/env bash

source "$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)/../etc/bash/common.lib.sh"

# Argument 1: Package path
test_package() {
    local exit_code=0

    print_header "Testing" "$(package_path_to_package_name "$1")"

    cd "$1" 2>/dev/null
    exit_on_error "Cannot change current directory to $1"

    if [[ "$(composer run-script --list 2> /dev/null | awk '{ print $1 }' | grep -c ^test$)" = "0" ]]; then
        run_phpspec "$1" || exit_code=$?
        run_phpunit "$1" || exit_code=$?
    else
        run_command "composer test" || exit_code=$?
    fi

    return ${exit_code}
}

# Argument 1: Package path
run_phpspec() {
    local phpspec
    if [[ ! -e "phpspec.yml.dist" && ! -e "phpspec.yml" ]]; then
        return 0
    fi

    phpspec="$(get_binary phpspec)"
    if [ "$?" != "0" ]; then
        print_error "Phpspec binary not found, make sure you included it in require-dev"
        return 1
    fi

    retry_run_command "${phpspec} run --ansi --no-interaction --format=dot"
}

# Argument 1: Package path
run_phpunit() {
    local phpunit
    if [[ ! -e "phpunit.xml.dist" && ! -e "phpunit.xml" ]]; then
        return 0
    fi

    phpunit="$(get_binary phpunit)"
    if [ "$?" != "0" ]; then
        print_error "Phpunit binary not found, make sure you included it in require-dev"
        return 1
    fi

    retry_run_command "${phpunit} --colors=always"
}

display_help_message() {
    print_error "Usage: $0 <package paths or names>"
}

main() {
    local packages=() options=() package_path

    while [[ $# -gt 0 ]]; do
        case "$1" in
            --help)
                display_help_message
                exit 0
            ;;
            -*)
                print_error "Unknown option \"$1\""
                exit 1
            ;;
            *)
               packages+=("$1")
            ;;
        esac

        shift
    done

    if [[ "${packages[@]}" = "" ]]; then
        display_help_message
        exit 1
    fi

    for package in "${packages[@]}"; do
        package_path="$(cast_package_argument_to_package_path "${package}")"
        exit_on_error "Package \"${package}\" is not found"

        test_package "${package_path}" "${options[*]}"
    done
}

main "$@"
