url.bash

#!/usr/bin/env bash

internet_url(){
    url="$(git config --get remote.origin.url | sed -r 's/.*(\@|\/\/)([^:\/]*)(\:|\/)(.*)(\.git)?/https:\/\/\2\/\4/')"
    url="${url%.git}"
    echo "$url"
}
ssh_url(){
    git config --get remote.origin.url | sed -r 's/.*(\@|\/\/)([^:\/]*)(\:|\/)(.*)\.git/git@\2:\4/'
}

git_host(){
    echo "$(internet_url)" | sed -r 's/^.*\/\/([^\.]*)\.[^\.]*\/.*$/\1/'
}

reponame_from_url(){
    url=""
    # echo "$1" | sed -r 's/^.*\/\/([^\.]*)\.[^\.]*\/.*$/\1/'
    echo "$1" | sed -r 's/^.+\/([^\.][^g][^i][^t]+)(\/|\.git)?$/\1/'
}


url(){
    # url [remote|name|ssh_key|url|new_account|default_branch|new_repo] [host_name]
    # host_name not needed if inside a repository, such as for default_branch and url
    repo="$(internet_url)"
    sshUrl="$(ssh_url)"
    default_host="github"
    default_host_url="https://github.com"
    if [[ -z ${repo} ]]; then
        repo="${default_host_url}"
    fi
    if [[ "$1" == "remote" ]];then
        echo "$(git config --get remote.origin.url)"
        return
    fi
    # decalare urls
    declare -A u
    u[github_name]="github"
    u[github_url]="${repo}"
    u[github_default_branch]="${repo}/settings/branches"
    u[github_ssh_key]="${repo}/settings/keys"
    u[github_new_repo]="https://github.com/new"
    u[github_new_account]="https://github.com/join/"
    u[github_delete]="${repo}/settings#danger-zone"

    u[bitbucket_name]="bitbucket"
    u[bitbucket_url]="${repo}"
    u[bitbucket_default_branch]="${repo}/admin"
    u[bitbucket_new_repo]="https://bitbucket.com/repo/create"
    u[bitbucket_new_account]="https://bitbucket.org/account/signup/"
    u[bitbucket_delete]="${repo}/admin"
    
    u[gitlab_name]="gitlab"
    u[gitlab_url]="${repo}"
    u[gitlab_ssh_url]="${sshUrl}"
    u[gitlab_default_branch]="${repo}/-/settings/repository#default-branch-settings"
    u[gitlab_ssh_key]="https://gitlab.com/profile/keys"
    u[gitlab_new_repo]="https://gitlab.com/projects/new"
    u[gitlab_new_account]="https://gitlab.com/users/sign_in#register-pane"
    u[gitlab_delete]="${repo}/edit#js-project-advanced-settings"
    
    # build dynamic params
    host=${2:-"$(git_host)"}
    if [[ -z ${host} ]];then
        host="${default_host}"
    fi
    # echo "${host}"
    for=${1:-"url"}
    
    # get value from dict
    # echo "--${host}--"
    key="${host}_${for}"
    val="${u[${key}]}"

    # url not found
    if [[ -z "${val}" ]];then
        echo "--url_not_found--"
        return;
    fi

    echo "${val}"
}