#!/bin/sh -e
#
# git-get - clones from resolving arguments and switches into the new directory
# args: see git-repo(1) all args beyond the first three are forwarded to git clone

remote=$(git-repo "$@")
printf '%s\n' "Cloning ${remote}"

test "$1" = "https" && shift

# shellcheck disable=SC2249
case "$#" in
  1)
    dir=$(basename "${remote%.git}")
    ;;
  3)
    # TODO: recognize shared prefix
    # shellcheck disable=SC2312
    test "$3" != "$(git config get user.name)" \
      && prefix=$(echo "$3" | sed "s|\(.\)\b.*$|\1|") \
      && case "$2" in
        "${prefix}"*) ;;
        "$(git config get user.name)") ;;
        *) dir="${prefix}_$2" ;;
      esac
    ;;
esac
case "$4" in
  -* | "") cdir="$2" ;;
  *) cdir="$4" ;;
esac

# shift "$(expr 3 \& $# \> 3 \| $#)"
shift "$((3 & $# > 3 | $#))"
git clone "${remote}" "$@" "${dir}" --recurse-submodules
cd "${dir:-${cdir}}"
exec
