#!/bin/sh -e

ORIGIN=$(git remote get-url origin 2>/dev/null)

if [ "${ORIGIN}" = "" ]; then
  echo "fatal: Not a git repository" >&2
  exit 1
fi

case "${ORIGIN}" in
  "git@"*)
    NEW_ORIGIN=$(echo "${ORIGIN}" | sed -e "s|^git@\([^:]*\):|https://\1/|" -e "s|.git$||")
    ;;
  "https://"*)
    NEW_ORIGIN=$(echo "${ORIGIN}" | sed -e "s|https://\([^/]*\)/|git@\1:|" -e "s|.git$||").git
    ;;
  *)
    echo "fatal: Unknown origin pattern: ${ORIGIN}" >&2
    exit 1
    ;;
esac

echo "Switching git origin: ${ORIGIN} -> ${NEW_ORIGIN}"
git remote set-url origin "${NEW_ORIGIN}"
if git branch | grep -q main; then
  git branch --set-upstream-to=origin/main main
fi
