#!/bin/bash
# Script to replace uses of 'realpath' and/or 'command -v'

echoerr() {
    cat <<< "$@" 1>&2
}

arb_realpath() {
    # replacement for 'realpath'
    #
    # Note: this function is duplicated in ../arb_install.sh@arb_realpath
    local FILE="$1"; shift

    local REALPATH=$(realpath    "$FILE" 2>/dev/null )
    local READLINK=$(readlink -f "$FILE" 2>/dev/null )

    if [ -z "${REALPATH}" ]; then
        if [ -z "${READLINK}" ]; then
            echoerr "Warning: neighter realpath nor readlink works here"
            if [ -e "${FILE}" ]; then
                local PWDFILE="$(pwd)/${FILE}"
                if [ -e "${PWDFILE}" ]; then echo "${PWDFILE}"
                else echo "${FILE}"
                fi
            else echo "${FILE}"
            fi
        else echo "${READLINK}"
        fi
    else
        if [ -z "${READLINK}" ]; then echo "${REALPATH}"
        else
            if [ "${READLINK}" != "${REALPATH}" ]; then
                echoerr "Warning: realpath and readlink differ (REALPATH=${REALPATH} READLINK=${READLINK})"
            fi
            echo "${REALPATH}"
        fi
    fi
}

arb_full_cmd() {
    # report full path of external command (as found by shell via PATH)
    local CMD="$1"; shift
    local FULLCMD=$(command -v "${CMD}" 2>/dev/null )
    if [ -n "${FULLCMD}" -a ! -x "${FULLCMD}" ]; then echoerr "[no valid full command for '${CMD}: '${FULLCMD}']"; FULLCMD=; fi
    if [ -z "${FULLCMD}" ]; then
        FULLCMD=$(hash -t "${CMD}" 2>/dev/null )
        if [ -n "${FULLCMD}" -a ! -x "${FULLCMD}" ]; then echoerr "[no valid full command for '${CMD}: '${FULLCMD}']"; FULLCMD=; fi
        if [ -z "${FULLCMD}" ]; then
            FULLCMD=$(which "${CMD}" 2>/dev/null )
            if [ -n "${FULLCMD}" -a ! -x "${FULLCMD}" ]; then echoerr "[no valid full command for '${CMD}: '${FULLCMD}']"; FULLCMD=; fi
        fi
    fi
    if [ -n "${FULLCMD}" ]; then
        FULLCMD=$(arb_realpath "${FULLCMD}")
    fi
    echo "${FULLCMD}"
}

usage_error() {
    local ERR="$1"; shift

    echoerr "Usage: arb_path.sh -r file"
    echoerr "       replacement for 'realpath file' (generates canonical pathname)."
    echoerr "       falls back to given input on failure to canonicalize."
    echoerr "Usage: arb_path.sh -x cmd"
    echoerr "       replacement for 'command -v file' (finds executable; absolute, relative or via PATH)."
    echoerr "       returns empty string if 'cmd' not found."
    echoerr ""
    echoerr "Error: ${ERR}"
    exit 1
}

FLAG="$1" ; shift
ARG="$1" ; shift

if [ -z "${ARG}" ]; then
    usage_error "missing argument(s)"
else
    if [ "${FLAG}" = "-r" ]; then
        echo $(arb_realpath "${ARG}")
    else
        if [ "${FLAG}" = "-x" ]; then
            echo $(arb_full_cmd "${ARG}")
        else
            usage_error "Unknown flag '${FLAG}'"
        fi
    fi
fi


