#!/bin/sh

set -eu

# This script is used to migrate local repository's remote to the new Gitea server.

NEW_GITEA_SERVER_URL="https://gitea.freeleaps.mathmast.com"

# Check current working directory is a git repository
if [ ! -d .git ]; then
  echo "Current working directory is not a git repository."
  exit 1
fi

# Check if the repository has a remote named 'origin'
if ! git remote get-url origin > /dev/null 2>&1; then
  echo "The repository does not have a remote named 'origin'."
  exit 1
fi

# Get current remote URL
current_remote_url=$(git remote get-url origin)

# Remove the existing remote named 'origin'
git remote remove origin

# Replace the remote URL with the new Gitea server URL
new_remote_url=$(echo "$current_remote_url" | sed "s#\(.*//\)[^/]*\(.*\)#$NEW_GITEA_SERVER_URL\2#")

# Add remote as 'origin'
git remote add origin "$new_remote_url"

echo "Remote URL has been updated to $new_remote_url"
echo "You can now push your changes to the new Gitea server using 'git push origin <branch>'"