#!/bin/bash

set -e

origin=$(git remote show origin)
if [[ $(echo "$origin" | awk -e '/https/') != "" ]]; then
	remote=$(git remote show origin | awk -e '/Fetch/' | cut -d ":" -f 3)
	git_host=$(echo "$remote" | cut -d "/" -f 3)
	git_repo=$(echo "$remote" | cut -d "/" -f 4-)
    git_branch=$(echo "$origin" | awk -e '/HEAD/' | cut -d ":" -f 2 | tr -d ' ')
    git remote remove origin
    git remote add origin git@$git_host:/$git_repo
    git fetch
    git branch --set-upstream-to=origin/$git_branch $git_branch
    echo "Updated to SSH url git@$git_host:/$git_repo, for branch $git_branch"
else
	remote=$(git remote show origin | awk -e '/Fetch/' | cut -d ":" -f 2-3)
    git_host=$(echo "$remote" | cut -d "@" -f 2 | cut -d ":" -f 1)
    git_repo=$(echo "$remote" | cut -d ":" -f 2 | cut -d "/" -f 2-)
    git_branch=$(echo "$origin" | awk -e '/HEAD/' | cut -d ":" -f 2 | tr -d ' ')
    git remote remove origin
    git remote add origin https://$git_host/$git_repo
    git fetch
    git branch --set-upstream-to=origin/$git_branch $git_branch
    echo "Updated to HTTPS url https://$git_host/$git_repo, for branch $git_branch"
fi
