#!/bin/sh
# Select an existing PHP 8 CLI without changing the website or system default.
set -eu

mode=${1:-configuration}
case "$mode" in
    configuration|connection|schema|lint) ;;
    *) printf '%s\n' 'Usage: sh backend/scripts/check_hosting.sh [configuration|connection|schema|lint]' >&2; exit 2 ;;
esac

php_bin=''
best_version=0
consider_php() {
    candidate=$1
    [ -x "$candidate" ] || return 0
    version=$("$candidate" -r 'if (PHP_SAPI === "cli") { echo PHP_VERSION_ID; }' 2>/dev/null) || return 0
    case "$version" in ''|*[!0-9]*) return 0 ;; esac
    if [ "$version" -ge 80000 ] && [ "$version" -lt 90000 ] && [ "$version" -gt "$best_version" ]; then
        php_bin=$candidate
        best_version=$version
    fi
}

if [ -n "${MYINFO_PHP_BIN:-}" ]; then
    consider_php "$MYINFO_PHP_BIN"
else
    for executable in "$(command -v php 2>/dev/null || true)" \
        /opt/cpanel/ea-php8*/root/usr/bin/php \
        /opt/alt/php8*/usr/bin/php \
        /opt/cloudlinux/alt-php8*/root/usr/bin/php; do
        consider_php "$executable"
    done
fi

if [ -z "$php_bin" ]; then
    printf '%s\n' 'FAIL: no runnable PHP 8.x CLI found. Ask hosting support for its path, then set MYINFO_PHP_BIN to that executable.' >&2
    exit 2
fi

script_dir=$(CDPATH='' cd -- "$(dirname -- "$0")" && pwd)
printf 'PHP CLI selected: %s\n' "$php_bin"
"$php_bin" -v

case "$mode" in
    configuration) exec "$php_bin" "$script_dir/../tests/configuration_test.php" ;;
    connection) exec "$php_bin" "$script_dir/test_connection.php" ;;
    schema) exec "$php_bin" "$script_dir/inspect_schema.php" ;;
    lint)
        for source in "$script_dir/../config/Environment.php" \
            "$script_dir/../config/bootstrap.php" \
            "$script_dir/../src/Database/Connection.php" \
            "$script_dir/../src/Database/SchemaInspector.php" \
            "$script_dir/../src/Database/SchemaReport.php" \
            "$script_dir/test_connection.php" \
            "$script_dir/inspect_schema.php" \
            "$script_dir/../tests/configuration_test.php" \
            "$script_dir/../tests/schema_report_test.php"; do
            "$php_bin" -l "$source"
        done
        ;;
esac
