#!/usr/bin/env bash

# Get current remote URL
currentURL=$(git config --get remote.origin.url)

# Exit early if no remote URL is set
if [[ -z "$currentURL" ]]; then
    echo "No remote.origin.url is set. Nothing to do."
    exit 0
fi

# Detect SSH format (e.g. git@github.com:user/repo.git)
if [[ "$currentURL" == git@*:* ]]; then
    # Extract host and path
    host="${currentURL#git@}"
    host="${host%%:*}"
    path="${currentURL#*:}"
    # Remove trailing .git if present
    path="${path%.git}"

    newURL="https://$host/$path"
    # Preserve .git if it was present
    [[ "$currentURL" == *.git ]] && newURL+=".git"

    direction="SSH ➝ HTTPS"

# Detect HTTPS format (e.g. https://github.com/user/repo.git)
elif [[ "$currentURL" == http*://*/* ]]; then
    # Strip protocol
    tmp="${currentURL#http://}"
    tmp="${tmp#https://}"
    host="${tmp%%/*}"
    path="${tmp#*/}"
    # Remove trailing .git if present
    path="${path%.git}"

    newURL="git@$host:$path"
    # Preserve .git if it was present
    [[ "$currentURL" == *.git ]] && newURL+=".git"

    direction="HTTPS ➝ SSH"

else
    echo "The current remote URL format is not recognized: $currentURL"
    exit 1
fi

# Confirm and apply
echo "Current URL: $currentURL"
echo "Target format: $direction"
echo "New URL: $newURL"
read -p "Do you want to apply this change? (y/n): " response

if [[ "$response" == "y" ]]; then
    git remote set-url origin "$newURL"
    echo "Git remote updated."
else
    echo "Git remote unchanged."
fi
