#!/usr/bin/env bash

# Helper function, modified from https://stackoverflow.com/a/28776166/6202029
is_sourced() {
    if [ -n "$ZSH_VERSION" ]; then
        case $ZSH_EVAL_CONTEXT in *:file:*) return 0;; esac
    else  # Add additional POSIX-compatible shell names here, if needed.
        case ${0##*/} in dash|-dash|bash|-bash|ksh|-ksh|sh|-sh|fish|-fish|csh|-csh|tcsh|-tcsh) return 0;; esac
    fi
    return 1  # NOT sourced.
}

# Choose the right python
if [ -z ${PYTHON_PATH:+x} ]; then
    type -t python > /dev/null && has_py=1 || has_py=0
    if [ $has_py -eq 1 ] && [ "$(python -c 'import sys; print(sys.version_info[0])' 2>&1)" -eq 3 ]; then
        PYTHON_PATH=python
    else
        type -t python3 > /dev/null && has_py3=1 || has_py3=0
        if [ $has_py3 -eq 1 ]; then
            PYTHON_PATH=python3
        else
            echo "Error: GitID requires Python 3. Please install it and try again." 1>&2
            exit 1
        fi
    fi
fi

stdout=$("${PYTHON_PATH}" -m gitid.main "$@" 2>&1)
ret=$?

if [[ $ret -eq 99 ]]; then
    is_sourced && sourced=1 || sourced=0
    if [[ $sourced -eq 1 ]]; then
        eval "${stdout}"
    else
        echo "Error: GitID was not invoked correctly! Have you run gitid init and restarted your shell?"
    fi
elif [[ -n "${stdout}" ]]; then
    echo "${stdout}"
fi
