#!/bin/sh

# Quickly set a fork url of a repository after cloning it
# Only works on Git Forge URL (e.g. GitHub, GitLab, Gitea, ...)
#
# NOTE: can also be run as 'git fork'

user='folliehiyuki'
upstream="$(git remote get-url origin)"

# Set the fork's URL scheme
target_scheme='ssh'
if [ $# -ge 1 ] && [ "$1" = '-s' ]; then
	target_scheme='https'
fi

# There is also 'git://website_url/project.git' pattern (e.g. Linux kernel, Emacs, ...)
if ! printf "%s" "${upstream}" | grep -qE '^(https?://|git@)[^/:]+[/:][^/:]+/[^/:]+(\.git)?$'; then
	echo "URL scheme is not supported."
	exit 1
fi

# Capture the information
forge_url="$(printf "%s" "${upstream}" | sed 's!\(https\?://\|git@\)\([^/:]\+\)[/:][^/:]\+/[^/:]\+\(\.git\)\?!\2!')"
project="$(printf "%s" "${upstream}" | sed 's!\(https\?://\|git@\)[^/:]\+[/:][^/:]\+/\([^/:]\+\)!\2!')"
# Add the '.git' suffix if missing
if ! printf "%s" "${project}" | grep -qE '.+\.git$'; then
	project="${project}.git"
fi

if [ "${target_scheme}" = 'ssh' ]; then
	origin="git@${forge_url}:${user}/${project}"
else
	origin="https://${forge_url}/${user}/${project}"
fi

# Don't fork your own repo :v
if [ ! "${origin}" = "${upstream}" ] && ( printf "%s" "${upstream}" | grep -qFv "${user}" ) ; then
	git remote add upstream "${upstream}"
fi

# set-url anyway in case we just want to switch protocol
git remote set-url origin "${origin}"
