#!/bin/bash
#
# SCRIPT: blade
# AUTHOR: Michaelpeng <michaelpeng@tencent.com>
#         Phongchen <phongchen@tencent.com>
# DATE:   Dec 17 2011
# REV:    1.0.P (Valid are A, B, D, T and P)
#               (For Alpha, Beta, Dev, Test and Production)
#
# PLATFORM: Linux, macOS
# PURPOSE : A bash wrapper that locates the blade core next to this
#           script and runs it with a suitable Python interpreter.
# REV LIST:
#        DATE:    Dec 17 2011
#        BY  :    Michaelpeng
#        MODIFICATION: Created

function _fatal() {
    if [ -t 2 ]; then
        echo -e "\033[1;31mBlade(fatal): $@\nBlade(fatal): Blade will exit...\033[m" >&2
    else
        echo -e "Blade(fatal): $@\nBlade(fatal): Blade will exit..." >&2
    fi
    exit 1
}

function _full_real_path() {
    local o f
    f="$1"

    if [ ! -L "$0" ]; then
        echo "$f"
        return 0
    fi

    if o=$(readlink -f "$f" 2>/dev/null); then
        echo "$o"
        return 0
    fi

    # BSD readlink doesn't support -f
    if o=$(readlink "$f"); then
        f="$o"
    fi

    echo "$(cd "$(dirname "$f")" && pwd)/$(basename "$f")"
    return 0
}

# Return 0 and echo the interpreter if "$1" is a single executable on PATH
# whose sys.version_info reports Python >= 3.10. Return 1 otherwise (silently).
# Multi-word values (e.g. "python -m coverage run ...") are intentionally
# rejected so that the full-command form stays routed through the final
# ${BLADE_PYTHON_INTERPRETER:-$python} fallback at the bottom of this
# script rather than being executed with a bare `-c`.
function _probe_python() {
    local candidate="$1"
    [ -n "$candidate" ] || return 1
    # Single-word check: reject if the value contains whitespace.
    case "$candidate" in
        *[[:space:]]*) return 1 ;;
    esac
    command -v "$candidate" &> /dev/null || return 1

    # Let Python judge its own version: sys.version_info is authoritative,
    # and reading the exit code (not stdout) makes this immune to stderr
    # banners/warnings that some shims emit.
    "$candidate" -c 'import sys; sys.exit(0 if sys.version_info >= (3, 10) else 1)' &> /dev/null \
        || return 1
    echo "$candidate"
    return 0
}

# Check the python version at first, exit blade when python
# version is under 3.10.
function _check_python() {
    # Honor BLADE_PYTHON_INTERPRETER when it names a single executable that
    # already satisfies the version requirement. This lets users point blade
    # at e.g. /opt/homebrew/bin/python3.12 without having to shadow the
    # system python3 on PATH. Multi-word values (coverage wrappers etc.)
    # silently fall through to auto-detection and are re-applied at the
    # final `${BLADE_PYTHON_INTERPRETER:-$python}` invocation below.
    local override
    if override=$(_probe_python "${BLADE_PYTHON_INTERPRETER:-}"); then
        echo "$override"
        return 0
    fi

    # Detection order:
    # 1. The generic names `python3` then `python` -- if present and >= 3.10.
    # 2. Specific versioned interpreters, newest first, so a too-old system
    #    `python3` still lets blade pick up a usable python elsewhere on PATH.
    local candidate found
    for candidate in python3 python \
                     python3.14 python3.13 python3.12 python3.11 python3.10; do
        if found=$(_probe_python "$candidate"); then
            echo "$found"
            return 0
        fi
    done

    # Nothing usable found.
    _fatal "No Python >= 3.10 found (tried python3, python, python3.14 .. python3.10). Please install python 3.10+."
}


blade_path=$(_full_real_path "$0")
blade_dir=$(cd "$(dirname "$blade_path")" && pwd)

if [[ -d "$blade_dir/src/blade" ]]; then
    blade_file="$blade_dir/src"
else
    blade_file="$blade_dir/blade.zip"
fi

if [[ -e "$blade_dir/blade_init" ]]; then
    source "$blade_dir/blade_init"
fi

# Note: _fatal inside _check_python runs in a command-substitution
# sub-shell, so its `exit 1` only terminates the sub-shell. Propagate
# the failure explicitly here.
python=$(_check_python) || exit 1

# Check ninja
if ! command -v ninja &> /dev/null; then
    _fatal "Please install ninja v1.8+ (https://ninja-build.org)"
fi

# Check blade file
if [[ ! -e "$blade_file" ]]; then
    _fatal "Cannot find the core file $blade_file"
fi

# BLADE_PYTHON_INTERPRETER is intentionally left unquoted: it may be a
# multi-word command (e.g. "python -m coverage run"). exec replaces this
# wrapper so signals propagate straight to blade and the exit code is blade's.
exec ${BLADE_PYTHON_INTERPRETER:-$python} "$blade_file" "$@"
