#!/bin/sh
#
# git-url - translate different repo notations into ssh
#
# usage:
#   git url <url>
#   git url <host> <repo> [user]

if command -v tailscale >/dev/null 2>&1; then
  TS_DOMAIN="$(tailscale status --self --json | jq -r '.CertDomains[0]')"
fi

# shellcheck disable=SC2249
case "$1" in
  http*)
    if expr "$1" : ".*:" >/dev/null; then
      echo "${1%/}" | sed "s|.*//\([^/]*\)/\(.*\)|git@\1:\2.git|"
      exit
    else
      http="$1" && shift
    fi
    ;;
  git:* | ssh:*)
    echo "$1"
    exit
    ;;
esac

host="$1"
# shellcheck disable=SC2249
case ${host} in
  hub | github)
    host=git@github.com
    ;;
  lab)
    host=git@gitlab.com
    ;;
  ts)
    host=git@${TS_DOMAIN}
    ;;
  go | "")
    host=git@git
    user=git
    ;;
esac

user=${3:-${user:-$(git config user.name)}}
# shellcheck disable=SC2312
repo=${2:-$(basename "$(gitroot)")}

if test "${http}"; then
  echo "${http}://${host#git*@}/${user}/${repo}.git"
else
  echo "${host}:${user}/${repo}.git"
fi
