#!/usr/bin/env bash
# libredbdiff
#
# Copyright (C) 2014 Esteban Carnevale <alfplayer@mailoo.org>
# Copyright (C) 2014, 2017 Luke Shumaker <lukeshu@sbcglobal.net>
# Copyright (C) 2020 André Silva <emulatorman@hyperbola.info>
# Copyright (C) 2020 Márcio Silva <coadde@hyperbola.info>
#
# 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 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/>.

set -euE -o pipefail
. "$(librelib messages)"
. "$(librelib conf)"
load_files libredbdiff || exit
setup_traps

declare -r name="Libredbdiff"
declare -r cmd="${0##*/}"

declare -r conffile_hyper="$statedir/pacman.conf.hyperbola"
declare -r conffile_arch="$statedir/pacman.conf.arch"

declare -r dbpath_hyper="$statedir/pacman.hyperbola"
declare -r dbpath_arch="$statedir/pacman.arch"

declare -r mirrorlist_hyper="$statedir/mirrorlist.hyperbola"
declare -r mirrorlist_arch="$statedir/mirrorlist.arch"

declare -r field_pkgname_hyper=30
declare -r field_pkgname_arch=30
declare -r field_pkgname_total="$((field_pkgname_hyper + field_pkgname_arch))"

declare -r printf_format="%s  %-${field_pkgname_hyper}s%-${field_pkgname_arch}s   %s | %s\n"
declare -r printf_format_noarch="%s  %-${field_pkgname_total}s   %s\n"

enablerepo() {
	local repo="$1"
	local conffile_arg="$2"

	msg2 "Enabling repo %q in %q" "$repo" "$conffile_arg"
	sed -i "s/\#\[$repo\]/[$repo]/" "$conffile_arg"
	sed -i "\/\[$repo\]/,+1 s/#Include/Include/" "$conffile_arg"
}

createdir() {
	local dir=$1

	if ! [[ -d "$dir" ]] ; then
		msg "Creating directory %q" "$dir"
		mkdir -- "$dir" || die "Failed to create directory %q.  Exiting." "$dir"
	fi
}

# {{ A -lt B }} is like [ A -lt B ], but for pacman version numbers
{{() {
	  [[ $# = 4 ]] || panic
	  [[ $4 = '}}' ]] || panic
	  local a=$1
	  local op=$2
	  local b=$3

	  local cmp
	  cmp="$(vercmp "$a" "$b")" || die "vercmp failed"
	  [ "$cmp" "$op" 0 ]
}

# Globals:
#  - pkgname  : the Hyperbola pkgname
#  - ver_hyper : a map of pkgname->arch_pkgver
#  - ver_arch : a map of pkgname->hyper_pkgver
#  - provides : a map of pkgname->provides
compare_pkgs() {
	if [[ -n "${ver_arch[$pkgname]:-}" ]]; then
		if {{ "${ver_hyper[$pkgname]}" -lt "${ver_arch[$pkgname]}" }}; then
			printf "$printf_format" \
				'=' \
				"$pkgname" \
				"" \
				"${ver_hyper[$pkgname]}" \
				"${ver_arch[$pkgname]}"
		fi
	elif [[ -n "${provides[$pkgname]:-}" ]]; then
		local _provides provide
		read -r -a _provides <<<"${provides[$pkgname]}"
		for provide in "${_provides[@]}"; do
			if [[ -n "${ver_arch[$provide]:-}" ]]; then
				if {{ "${ver_hyper[$pkgname]}" -lt "${ver_arch[$provide]}" }}; then
					printf "$printf_format" \
						'p' \
						"$pkgname" \
						"$provide" \
						"${ver_hyper[$pkgname]}" \
						"${ver_arch[$provide]}"
				fi
			fi
		done
	else
		printf "$printf_format_noarch" \
			'o' \
			"$pkgname" \
			"${ver_hyper[$pkgname]}"
	fi
}

# Globals:
#  - hyper_packages_tmp
#  - ver_hyper
#  - ver_arch (transitively through compare_pkgs)
#  - provides
print_cmp() {
	local repo="$1"

	< "$hyper_packages_tmp" \
		awk -F/ -v repo="$repo" '$1 == repo {print $2}' |
		while read -r pkgname _pkgver _provides ; do
			ver_hyper["$pkgname"]="$_pkgver"
			provides["$pkgname"]="$_provides"
			compare_pkgs
		done
}

usage() {
	print "Usage: doas %q" "$cmd"
	print "   or: %q -n [REPO]" "$cmd"
	print "   or: %q -h" "$cmd"
	print 'Show packages that need to be updated from Arch repositories.'
	echo
	prose "Compares packages in Hyperbola repositories.  Packages from
	       all configured Hyperbola repositories are compared.  A Hyperbola
	       repository name can be specified as argument to compare only
	       packages in that repository."
	echo
	prose "The default mode of operation requires root, and downloads or
	       updates all necessary files for comparison, but does not compare
	       them.  After that mode has been run, run the tool again without
	       root with the the \`-n\` flag to not download anything, but to
	       compare the already downloaded files."
	echo
	prose "In the compare mode (if the \`-n\` flag is given), by default it
	       will iterate over each of the configured repositories, prefixing
	       each section with a line in the format \`[REPO]\`.  However, if a
	       REPO is specified on the command line, it scan for packages only
	       in that repository, and no \`[REPO]\` line will be printed."
	echo
	print 'Options:'
	flag '-n' "Don't update anything, just compare already downloaded files."
	flag '-h' 'Show this message'
	echo
	prose "In the compare mode the output is in the format:"
	echo
	print '\t[repo]'
	print '\tpkgline'
	print '\tpkgline'
	print '\t...'
	print '\t[repo]'
	print '\tpkgline'
	print '\tpkgline'
	print '\t...'
	echo
	prose "That is, the output is organized by Hyperbola repository, and
	       within each repository section, there is one line for each
	       package in that Hyperbola repo that seems to be behind the
	       equivalent package in Arch."
	echo
	print "The line-format for packages is:"
	printf "\t$printf_format" \
	       status hyperbola_pkgname '[arch_pkgname]' hyperbola_pkgver arch_pkgver
	echo
	print "Where 'status' is one of the characters:"
	flag '=' "An Arch package with the same pkgname as a Hyperbola package
	          was found, and Arch has a higher pkgver than Hyperbola.  In
	          this case, arch_pkgname is not present (as it is the same as
	          the hyperbola_pkgname)."
	flag 'p' "An Arch package with a pkgname that is provide'd by a Hyperbola
	          package was found, and the pkgver of the Arch package is
	          higher than the pkgver of the hyperbola package."
	flag 'o' "It appears that this Hyperbola package is not a replacement for
	          an Arch package."
}

main() {
	local args arg mode=update badargs=false
	args="$(getopt -n "$cmd" -o nh -l noupdate,help -- "$@")" || badargs=true
	eval "set -- $args"
	while [[ $# -gt 0 ]]; do
		arg=$1
		shift
		case "$arg" in
			-n|--noupdate)
				mode=compare
				;;
			-h|--help)
				usage
				return 0
				;;
			--)
				break
				;;
		esac
	done
	if $badargs; then
		usage >&2
		return 2
	fi

	case $mode in
		update)
			if [[ $# -gt 0 ]]; then
				print "%s: found non-flag arguments; a repo list may only be specified with the -n flag: %s" "$cmd" "$*" >&2
				usage >&2
				return 2
			fi
			main_update
			;;
		compare)
			if [[ $# -gt 1 ]]; then
				print "%s: found too many non-flag arguments; only one repo may be specified: %s" "$cmd" "$*" >&2
				usage >&2
				return 2
			fi
			if [[ $# = 1 ]]; then
				if ! in_array "$1" "${repos[@]}"; then
					die "The specified Hyperbola repo \"%s\" cannot be compared.  It's not in the list of repos in the configuration variable \"repos\"." "$1"
				fi
			fi
			main_compare "$@"
			;;
	esac
}

main_update() {
	if [[ $EUID != 0 ]]; then
		error "Must run as root to initialize or update %s databases." "$cmd"
		usage >&2
		exit 1
	fi
	check_vars libredbdiff statedir mirror_hyper mirror_arch || exit 1

	createdir "$statedir"
	{
		msg "Generating %s %q" Hyperbola pacman.conf
		cp -T /usr/share/pacman/defaults/pacman.conf.x86_64 "$conffile_hyper"
		sed -r \
		    -e "s|/etc/pacman\.d/mirrorlist$|$mirrorlist_hyper|" \
		    -e "s|^#?DBPath\s*=.*|DBPath = $dbpath_hyper|" \
		    -e "s|^#?Architecture\s*=.*|Architecture = x86_64|" \
		    -i "$conffile_hyper"
		local repo
		for repo in multilib; do
			enablerepo "$repo" "$conffile_hyper"
		done

		msg "Generating %s %q" Arch pacman.conf
		wget -q \
		     -O "$conffile_arch" \
		     "https://git.archlinux.org/svntogit/packages.git/plain/pacman/repos/core-x86_64/pacman.conf.x86_64" ||
			die "Failed to download %q.  Exiting." "$conffile_arch"
		sed -r \
		    -e "s|/etc/pacman\.d/mirrorlist$|$mirrorlist_arch|" \
		    -e "s|^#?DBPath\s*=.*|DBPath = $dbpath_arch|" \
		    -e "s|^#?Architecture\s*=.*|Architecture = x86_64|" \
		    -i "$conffile_arch"
		enablerepo multilib "$conffile_arch"

		printf 'Server = %s\n' "$mirror_hyper" > "$mirrorlist_hyper"

		printf 'Server = %s\n' "${mirror_arch/SNAPSHOT/${SNAPSHOT//-//}}" > "$mirrorlist_arch"
	}

	createdir "$dbpath_hyper"
	{
		msg "Synchronizing %s pacman databases for %s" "$name" "Hyperbola"
		pacman --config "$conffile_hyper" -Sy ||
			die "Failed to synchronize pacman database for %s.  Exiting." Hyperbola
	}

	createdir "$dbpath_arch"
	{
		msg "Synchronizing %s pacman databases for %s" "$name" "Arch"
		pacman --config "$conffile_arch" -Sy ||
			die "Failed to synchronize pacman database for %s.  Exiting." Arch
	}

	msg "%s pacman databases are updated.  %s is ready.  Run %q -n to print results." \
	    "$name" "$name" "$cmd"
}

main_compare() {
	check_vars libredbdiff statedir repos || exit 1

	if ! [[ -f "$conffile_hyper" && \
	        -f "$conffile_arch" && \
	        -f "$dbpath_hyper/sync/core.db" && \
		-f "$dbpath_arch/sync/core.db" ]]
	then
		error "You must run %q with out arguments as root to initialize." "$cmd"
		usage >&2
		exit 1
	fi

	local tmpdir
	tmpdir="$(mktemp --tmpdir -d "$cmd.XXXXXXXXXX")" || die "Could not create temporary working directory"
	trap "rm -rf -- $(printf %q "$tmpdir")" RETURN
	local arch_packages_tmp="$tmpdir/arch-packages"
	local hyper_packages_tmp="$tmpdir/hyperbola-packages"

	unset provides ver_hyper ver_arch
	declare -gA provides ver_hyper ver_arch

	expac --config "$conffile_arch" -S '%n %v' \
		> "$arch_packages_tmp" || \
		die "expac command to get %s package data has failed.  Exiting." Arch

	local pkgname pkgver
	while read -r pkgname pkgver; do
		ver_arch["$pkgname"]="$pkgver"
	done < "$arch_packages_tmp"

	expac --config "$conffile_hyper" -S '%r/%n %v %S' \
		> "$hyper_packages_tmp" || \
		die "expac command to get %s package data has failed.  Exiting." Hyperbola

	if [[ $# == 1 ]]; then
		print_cmp "$1"
	else
		for repo in "${repos[@]}" ; do
			echo "[$repo]"
			print_cmp "$repo"
		done
	fi
}

main "$@"
