#!/usr/bin/env bash
set -euo pipefail

ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
ADMIN="${ROOT}/admin"

run_php_syntax() {
    find "${ROOT}/includes" "${ROOT}/tests" -name '*.php' -print0 \
        | xargs -0 -n1 php -l
}

run_test() {
    composer --working-dir="${ROOT}" test
    # Licensing regressions declare their own WordPress stubs, so they cannot
    # share a PHPUnit process with the enumerated suite.
    "${ROOT}/tests/run-unit-tests.sh" \
        "${ROOT}/tests/unit/Licensing/LicenseStorageKeyStandaloneTest.php" \
        "${ROOT}/tests/unit/Licensing/ActiveClientResponseStandaloneTest.php" \
        "${ROOT}/tests/unit/Licensing/UpdatePackageVerificationStandaloneTest.php"
}

run_phpcs() {
    composer --working-dir="${ROOT}" phpcs
}

run_phpstan() {
    composer --working-dir="${ROOT}" phpstan
}

run_admin_lint() {
    npm --prefix "${ADMIN}" run lint:js
}

run_build() {
    npm --prefix "${ADMIN}" run build
}

case "${1:-all}" in
    php-syntax) run_php_syntax ;;
    test) run_test ;;
    phpcs) run_phpcs ;;
    phpstan) run_phpstan ;;
    admin-lint) run_admin_lint ;;
    build) run_build ;;
    all)
        run_php_syntax
        run_test
        run_phpcs
        run_phpstan
        run_admin_lint
        run_build
        ;;
    *)
        printf 'Usage: %s {all|php-syntax|test|phpcs|phpstan|admin-lint|build}\n' "$0" >&2
        exit 64
        ;;
esac
