#!/usr/bin/env bash

OLD_URL=$(git remote get-url origin)
if [[ $OLD_URL == "https://github.com"* ]]; then
	# Modified sed pattern to better handle GitHub URLs
	USER_REPO=$(echo $OLD_URL | sed -n 's|https://github.com/\([^/]*/[^/]*\)|\1|p')
	if [ -z "$USER_REPO" ]; then
		echo "Error: Could not extract user/repo from URL: $OLD_URL"
		exit 1
	fi

	# Remove any trailing .git if present and add it back consistently
	USER_REPO=$(echo $USER_REPO | sed 's/\.git$//')
	NEW_URL="git@github.com:${USER_REPO}.git"

	echo "Old URL: $OLD_URL"
	echo "New URL: $NEW_URL"

	# Update the remote URL to use SSH
	git remote set-url origin "$NEW_URL"

	# Verify the change
	CURRENT_URL=$(git remote get-url origin)
	if [ "$CURRENT_URL" = "$NEW_URL" ]; then
		echo "Successfully updated remote URL to use SSH."
	else
		echo "Error: Failed to update remote URL."
		exit 1
	fi
else
	echo "Remote URL is already using SSH or a different protocol: $OLD_URL"
fi
