#!/usr/bin/env bash
# Shows a diff between repo databases

# Copyright (C) 2013 Nicolás Reynolds <fauno@parabola.nu>
# Copyright (C) 2017, 2024 Luke T. Shumaker <lukeshu@parabola.nu>
#
# License: GNU GPLv3+
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

. "$(librelib messages)"

usage() {
	print "Usage: %s [OPTIONS] arch/core/i686 parabola/core/i686" "${0##*/}"
	print "Compares two repo databases using distro/repo/architecture format."
	echo
	print 'Shortcuts:'
	flag \
		'arch' 'expands to Arch Linux repo url' \
		'parabola' 'expands to Parabola GNU/Linux-libre repo url'
	echo
	print 'Options:'
	flag \
		'-h, --help' 'Show this message'
}

b() {
	bsdtar tf "$1" | cut -d "/" -f1 | sort -u
}
n() {
	tr "/" "-" <<<"$1".db
}

# hopefully simple way to convert
# parabola/libre/i686
# to
# http://repo.parabola.nu/libre/os/i686/libre.db
# add more distros here
g() {
	sed <<<"$1" \
		-e "s,^\([^/]\+\)/\([^/]\+\)/\([^/]\+\)$,\1/\2/os/\3/\2.db," \
		-e "s,^parabola/,http://repo.parabola.nu/," \
		-e "s,^arch\(linux\)\?/,http://mirrors.kernel.org/archlinux/,"
}

main() {
	local args mode=run
	if ! args="$(getopt -n "${0##*/}" -o 'h' -l 'help' -- "$@")"; then
		mode=errusage
	else
		eval "set -- $args"
		local flag
		while true; do
			flag=$1
			shift
			case "$flag" in
				-h | --help) mode=usage ;;
				--) break ;;
				*) panic 'unhandled flag: %q' "$flag" ;;
			esac
		done
		if [[ $mode == run && $# -ne 2 ]]; then
			gnuerror 'expected 2 non-flag arguments, got %d' "$#"
			mode=errusage
		fi
	fi
	case "$mode" in
		errusage)
			print "Try '%s --help' for more information." "${0##*/}" >&2
			return $EXIT_INVALIDARGUMENT
			;;
		usage)
			usage
			return $EXIT_SUCCESS
			;;
		run) : ;;
		*) panic 'invalid mode: %q' "$mode" ;;
	esac

	local tmpdir
	tmpdir="$(mktemp -d -t "${0##*/}.XXXXXXXXXX")"
	pushd "$tmpdir" >/dev/null

	d=""
	for i in "$1" "$2"; do
		n=$(n "$i")

		[[ -n $n ]] || exit $EXIT_FAILURE

		wget -O "$n" -nv "$(g "$i")"
		b "$n" >"${n}.orig"

		d+=" ${n}.orig"
	done

	{
		print 'Difference between %s and %s' "$1" "$2"
		echo '---'
		if type diffstat &>/dev/null; then
			diff -auN "${d[@]}" | diffstat
		fi
		diff -auN "${d[@]}"
	} >"../${n}.diff"

	popd >/dev/null
	rm -r "$tmpdir"

	print "Difference save on %s" "${n}.diff"
}

main "$@"
