#!/usr/bin/env bash
# SPDX-License-Identifier: MIT
# ──────────────────────────────────────────────────────────────────────────────
# $source: cappysan-dotfile-scripts$
# ──────────────────────────────────────────────────────────────────────────────
#
# Used as a symlink so that a command: `foobar one` tries to call `foobar-one`
# before resolving to `foobar one`.
#
# Example for `docker`, which can now accept `docker upgrade`:
# ~~~
# ls -la
#   bin/docker -> _subcommand
#   bin/docker-upgrade
# ~~~
set -eu -o pipefail

as_cmd=""
this=$(basename ${0})

# If there's a first argument, search for "$0-$1" in PATH
if test -n "${1:-}"; then
  as_cmd=$(type -pa "${this}-${1}" | head -1 2>/dev/null || true)
  # We exist as $0-$1, so call it instead
  if test -n "${as_cmd}"; then
    # discard the first argument, since it's the sub part
    # in "cmd-sub args"
    shift
    builtin command ${as_cmd} "$@"
    exit $?
  fi
fi

# If command is not a file on disk, it's on PATH.
if test ! -f "${as_cmd}"; then
  # We got called first, get the following one in PATH
  as_cmd=$(type -pa "${this}" | head -2 | tail -1)
  builtin command ${as_cmd} "$@"
else
  builtin command ${as_cmd} "$@"
fi
