#!/bin/bash

. "$(dirname "$(readlink -e "$0")")/config"
. "$(dirname "$(readlink -e "$0")")/db-functions"

if (( $# < 3 )); then
	msg "usage: %s <repo> <arch> <pkgname|pkgbase> ..." "${0##*/}"
	exit 1
fi

repo="$1"
arch="$2"
pkgbases=("${@:3}")

if ! check_repo_permission "$repo"; then
	die "You don't have permission to remove packages from %s" "$repo"
fi

if [[ $arch = any ]]; then
	tarches=("${ARCHES[@]}")
else
	tarches=("$arch")
fi

msg "Removing packages from [%s]..." "$repo"

for tarch in "${tarches[@]}"; do
	repo_lock "$repo" "$tarch" || exit 1
	declare -a remove_pkgs_$tarch
done
for pkgbase in "${pkgbases[@]}"; do
	for tarch in "${tarches[@]}"; do
		msg2 "%s (%s)" "$pkgbase" "$tarch"
		declare -n remove_pkgs="remove_pkgs_${tarch}"
		# We could just use %n and a single `mapfile`, but
		# getting extra info and printing everything is more
		# user-friendly.
		found=false
		while read -r _pkgbase pkgname pkgver; do
			plain 'pkgname=%s (%s)' "${pkgname}" "$pkgver"
			[[ $_pkgbase != '(null)' ]] || _pkgbase=$pkgname
			if [[ $_pkgbase != $pkgbase ]]; then
				warning "'%s' is a member of pkgbase=%s" "$pkgname" "$_pkgbase"
				warning "It is the only member being removed;"
				warning "you will need to remove the others yourself!"
			fi

			remove_pkgs+=("${pkgname}")
			found=true
		done < <(arch_expac_pkgbase "$repo" "$tarch" '%e %n %v' "$pkgbase")
		[[ $found = true ]] || plain '(none)'
		vcs_remove "$repo" "$tarch" "$pkgbase"
	done
done

for tarch in "${tarches[@]}"; do
	declare -n remove_pkgs="remove_pkgs_${tarch}"
	arch_repo_modify remove "${repo}" "${tarch}" "${remove_pkgs[@]}"
	repo_unlock "$repo" "$tarch"
done
