#!/bin/sh
# TokenEconomizer command line (`te status`, `te toolprune show`, `te config`, ...).
# Windows (Git Bash): see te-hook for the backslashes in $0 and the Microsoft Store alias.
self=$0
if [ "${OS:-}" = Windows_NT ]; then
  case $self in *\\*) self=$(printf '%s' "$self" | tr '\\' '/') ;; esac
fi
dir=$(CDPATH= cd -- "${self%/*}" && pwd)
# Session logs are UTF-8; without this, Python on Windows reads them in the ANSI code page.
export PYTHONUTF8=1
outside_windowsapps() {
  set -f; _ifs=$IFS; IFS=:
  for _d in $PATH; do
    case $_d in ''|*WindowsApps*) continue ;; esac
    for _f in "$_d/$1.exe" "$_d/$1"; do
      if [ -f "$_f" ] && [ -x "$_f" ]; then IFS=$_ifs; set +f; printf '%s\n' "$_f"; return 0; fi
    done
  done
  IFS=$_ifs; set +f; return 1
}
if [ "${OS:-}" = Windows_NT ]; then
  for py in "${TE_PYTHON:-}" python3 python py; do
    [ -n "$py" ] && p=$(command -v "$py" 2>/dev/null) || continue
    case $p in *WindowsApps*) p=$(outside_windowsapps "$py") || continue ;; esac
    [ "$py" = py ] && exec "$p" -3 "$dir/te_bootstrap.py" cli "$@"
    exec "$p" "$dir/te_bootstrap.py" cli "$@"
  done
  for py in "${TE_PYTHON:-}" python3 python py; do
    [ -n "$py" ] && command -v "$py" >/dev/null 2>&1 || continue
    "$py" -c "" </dev/null >/dev/null 2>&1 || continue
    [ "$py" = py ] && exec py -3 "$dir/te_bootstrap.py" cli "$@"
    exec "$py" "$dir/te_bootstrap.py" cli "$@"
  done
else
  for py in "${TE_PYTHON:-}" python3 python; do
    [ -n "$py" ] && command -v "$py" >/dev/null 2>&1 || continue
    exec "$py" "$dir/te_bootstrap.py" cli "$@"
  done
fi
echo "te: no python3 on PATH (set TE_PYTHON)" >&2
exit 1
