#!/usr/bin/bash

# for +() in request
shopt -s extglob

function filter {
	echo "${@//+/%2B}"
}

function show_req {
	xdg-open "https://$BS/request/show/$1"
}

function show_pkg {
	local PRJ="$(filter "$1")"
	local PKG="$(filter "$2")"
	xdg-open "https://$BS/package/show/$PRJ/$PKG"
}

function show_pkg_joined {
	show_pkg "${1%/*}" "${1#*/}"
}

function show_prj {
	local PRJ="$(filter "$1")"
	xdg-open "https://$BS/project/monitor/$PRJ"
}

function show_devel {
	local PKG="$(osc develproject openSUSE:Factory "$1")" || exit 1
	show_pkg_joined "$PKG"
}

function show_factory {
	show_pkg openSUSE:Factory "$1"
}

BS=build.opensuse.org
DEVEL=0
FACTORY=0

while getopts "dfip" OPT; do
	case "$OPT" in
	d) DEVEL=1
	;;
	f) FACTORY=1
	;;
	i) BS=build.suse.de
	;;
	p) BS=pmbs.links2linux.de
	;;
	esac
done

shift $(($OPTIND-1))

if [ $DEVEL -eq 1 ]; then
	show_devel "$1"
elif [ $FACTORY -eq 1 ]; then
	show_factory "$1"
elif [ $# -eq 1 ]; then
	case "$1" in
	+([0-9]))
		show_req "$1"
		;;
	*/*)
		show_pkg_joined "$1"
		;;
	*)
		show_prj "$1"
		;;
	esac
elif [ $# -eq 2 ]; then
	show_pkg "$1" "$2"
else
	exit 1
fi
