#!/bin/sh
#
# Obtain commit URL from Redhat or Fedora dist-git

# Something like:
# https://src.fedoraproject.org/rpms/dnsmasq/c/d2f1660dbcf6811c0c1796a0392bbfa8a4574a8d?branch=master
# just from commit mentioned inside git repository

GIT=git
BRANCH="$(git branch | grep '^* ' | cut -d' ' -f 2-)"
REMOTE=$(git config --get "branch.$BRANCH.remote")
[ -z "$REMOTE" ] && REMOTE=origin
ORIGIN_URL=$(git remote get-url $REMOTE)

if [ $? -gt 0 ]; then
	echo "Failed to get origin" 2>&1
	exit 1
fi

HOST_PACKAGE=$(echo "$ORIGIN_URL" | sed \
	-e 's,^[a-z]\+://\([^@]\+@\)\?\([^/]\+\)/\([[:alnum:][:punct:]]\+\)\.git$,\2 \3,' \
	-e 's|^[a-z]\+://\([^@]\+@\)\?\([^/]\+\)/\([[:alnum:][:punct:]]\+\)$|\2 \3|' \
	-e 's|^\([^@]\+@\)\?\([^/]\+\):\([[:alnum:][:punct:]]\+\).git$|\2 \3|' \
)

HOST=$(echo "$HOST_PACKAGE" | cut -d' ' -f1)
HOSTPATH=$(echo "$HOST_PACKAGE" | cut -d' ' -f2)
URL_PREFIX=
URL_SUFFIX=

# pass hostname and receive template for URLs
# configuration is quite primitive. Just two columns,
# first is hostname, second is URL template
# Takes file argument and hostname
read_config()
{
	while read HOSTNAME TEMPLATE; do
		if [ "$HOSTNAME" = "$1" ]; then
			echo "$TEMPLATE"
		fi
	done
}

default_urls()
{
	cat << EOF
src.fedoraproject.org	https://src.fedoraproject.org/%{path}/c/%{commit}
pkgs.fedoraproject.org	https://src.fedoraproject.org/%{path}/c/%{commit}
pagure.io	https://pagure.io/%{path}/c/%{commit}
github.com	https://github.com/%{path}/commit/%{commit}
gitlab.com	https://gitlab.com/%{path}/commit/%{commit}
gitlab.isc.org	https://gitlab.isc.org/%{path}/commit/%{commit}
gitlab.freedesktop.org	https://gitlab.freedesktop.org/%{path}/commit/%{commit}
salsa.debian.org	https://salsa.debian.org/%{path}/commit/%{commit}
EOF
}

get_format_url()
{
	USER_CONFIG="$HOME/.config/git-commit-urls.conf"
	SYSTEM_CONFIG="/etc/git-commit-urls.conf"

	TEMPLATE=
	if [ -r "$USER_CONFIG" ]; then
		TEMPLATE=$(read_config "$1" < "$USER_CONFIG")
	fi
	if [ -z "$TEMPLATE" -a -r "$SYSTEM_CONFIG" ]; then
		TEMPLATE=$(read_config "$1" < "$SYSTEM_CONFIG")
	fi

	if [ -z "$TEMPLATE" ]; then
	# still not found or no configuration. Use some defaults
		TEMPLATE=$(default_urls | read_config "$1")
	fi
	echo "$TEMPLATE"
}

print_commits()
{
	$GIT rev-list --no-walk $@ | while read COMMIT; do
		echo "$TEMPLATE" | sed -e "s|%{path}|$HOSTPATH|g" -e "s|%{commit}|$COMMIT|g"
	done
}

if [ "$HOST_PACKAGE" = "$ORIGIN_URL" ]; then
	echo "Remote URL $ORIGIN_URL is not in supported format" 2>&1
	# echo "$HOST_PACKAGE"
	exit 1
fi

TEMPLATE=$(get_format_url $HOST)
if [ -z "$TEMPLATE" ]; then
	echo "Unsupported remote $ORIGIN_URL" 2>&1
	exit 1
fi

if [ -n "$1" ]; then
	print_commits "$@"
else
	print_commits HEAD
fi
