#!/usr/bin/env bash
{ set +x; } 2>/dev/null

# find all python binaries (pythonX.Y)
# exclude:
# python (without version)
# pythonX.Y-config
# pythonX.Ymu (--with-pymalloc --with-wide-unicode)
# pythonX.Ym (--with-pymalloc)

[[ -z $PATH ]] && echo "ERROR: \$PATH '' EMPTY" && exit 1

IFS=':';set -- $PATH;IFS=

find="$(find "$@" -name "python*" 2> /dev/null | sort -u | grep -E "/python\w.\w"$ | grep -v "pypy")"
finded=
set --;while IFS= read path; do
  ! [ -e "$path" ] && continue # symlink target must exists
  file="$(file "$path")" || continue
  # 1) executable
  # 2) symbolic link to
  # 3) unknown. script?
   [[ "$file" == *"executable"* ]] && {
        [[ "$@" == *"${path##*/}"* ]] && continue
        set -- "$@" "$path"; continue
   }
   [[ "$file" == *"symbolic"* ]] && {
        [[ $OSTYPE == *"darwin"* ]] && path="$(readlink "$path")"
        [[ $OSTYPE != *"darwin"* ]] && path="$(readlink -f "$path")"
        [[ $path =~ [0-9]+$ ]] || continue
        [[ "$@" == *"${path##*/}"* ]] && continue
        set -- "$@" "$path"; continue
   }
    echo "ERROR: $path is not binary file" 1>&2
done <<< "$find"
[[ $# == 0 ]] && echo "ERROR: 0 python binaries" && exit 1
find="$(while :; do echo "$1"; shift; [[ $# == 0 ]] && break; done)"
v=
[[ $OSTYPE == *darwin* ]] && {
    v=$(defaults read com.apple.versioner.python Version 2> /dev/null)
}
[[ -n $v ]] && {
  # run default version first
  find="$(echo "$find" | grep "$v";echo "$find" | grep -v "$v")";:
} || {
    echo "$find"
}
:

