#!/hint/bash
#
# SPDX-License-Identifier: GPL-3.0-or-later

[[ -z ${DEVTOOLS_INCLUDE_DB_MOVE_SH:-} ]] || return 0
DEVTOOLS_INCLUDE_DB_MOVE_SH=1

_DEVTOOLS_LIBRARY_DIR=${_DEVTOOLS_LIBRARY_DIR:-@pkgdatadir@}
# shellcheck source=src/lib/common.sh
source "${_DEVTOOLS_LIBRARY_DIR}"/lib/common.sh
# shellcheck source=src/lib/valid-repos.sh
source "${_DEVTOOLS_LIBRARY_DIR}"/lib/valid-repos.sh

set -e


pkgctl_db_move_usage() {
	local -r COMMAND=${_DEVTOOLS_COMMAND:-${BASH_SOURCE[0]##*/}}
	cat <<- _EOF_
		Usage: ${COMMAND} [OPTIONS] [SOURCE_REPO] [TARGET_REPO] [PKGBASE]...

		Move packages between binary repositories.

		OPTIONS
		    -y, --yes          Do not ask for confirmation
		    -h, --help         Show this help text

		EXAMPLES
		    $ ${COMMAND} extra-staging extra-testing libfoo libbar
		    $ ${COMMAND} extra core libfoo libbar
_EOF_
}

pkgctl_db_move() {
	if (( $# < 3 )); then
		pkgctl_db_move_usage
		exit 1
	fi

	local CONFIRM=1

	# option checking
	while (( $# )); do
		case $1 in
			-h|--help)
				pkgctl_db_move_usage
				exit 0
				;;
			-y|--yes)
				CONFIRM=0
				shift
				;;
			-*)
				die "invalid argument: %s" "$1"
				;;
			*)
				break
				;;
		esac
	done

	local source_repo=$1
	local target_repo=$2
	shift 2

	if ! in_array "${source_repo}" "${DEVTOOLS_VALID_REPOS[@]}"; then
		die "Invalid source repository: %s" "${source_repo}"
	fi
	if ! in_array "${target_repo}" "${DEVTOOLS_VALID_REPOS[@]}"; then
		die "Invalid target repository: %s" "${target_repo}"
	fi

	if (( CONFIRM )); then
		local pkglist
		pkglist=$(printf '%s\n' "$@" | paste -sd ' ')
		read -r -p "Move packages from [${source_repo}] to [${target_repo}]: ${pkglist}? [Y/n] " response
		case ${response} in
			[Yy][Ee][Ss]|[Yy]|'')
				: # continue
				;;
			*)
				exit 0
				;;
		esac
	fi

	local pkgbase
	for pkgbase in "$@"; do
		msg "Moving [%s] from [%s] to [%s]" "${pkgbase}" "${source_repo}" "${target_repo}"
		# shellcheck disable=SC2046
		db-move "${source_repo}" "${target_repo}" $(pacman -Sql "${source_repo}" | grep "^${pkgbase}" || echo "${pkgbase}")
	done
}
