#!/usr/bin/env bash
# Copyright (C) 2011-2012 Nicolás Reynolds <fauno@parabola.nu>
# Copyright (C) 2011-2012 Joshua Ismael Haase Hernández (xihh) <hahj87@gmail.com>
# Copyright (C) 2013, 2017, 2024 Luke T. Shumaker <lukeshu@parabola.nu>
#
# License: GNU GPLv3+
#
# This file is part of Parabola.
#
# Parabola 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.
#
# Parabola 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 Parabola. If not, see <http://www.gnu.org/licenses/>.

. "$(librelib messages)"

usage() {
	print "Usage: %s PKGNAME [PKGVER]" "${0##*/}"
	print '   or: %s {-h|--help}' "${0##*/}"
	print 'Detect if a given package (version) is already in the repos.'
	echo
	prose "If a version is specified, it assumed that you want a greater or
	       equal version."
	echo
	prose "Example usage:"
	print "  $ %s 'pcre' '20'" "${0##*/}"
	echo
	print 'Options:'
	flag \
		'-h, --help' 'Show this message'
	echo
	print "Exit status:"
	print "  0: The package is built"
	print "  1: The package has not built"
	print " >1: There was an error"
}

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 1 && $# -ne 2 ]]; then
			gnuerror 'requires 1 or 2 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

	pkg=${1}
	ver=${2:-0}

	r=0
	pver=$(LC_ALL=C pacman -Sddp --print-format '%v' "${pkg}" 2>/dev/null) || r=$?

	result=$(vercmp "${pver}" "${ver}")
	# result:
	# -1 : pver < ver
	#  0 : pver = ver
	#  1 : pver > ver

	if [[ $result -ge 0 ]] && [[ $r -eq 0 ]]; then
		exit $EXIT_TRUE
	else
		exit $EXIT_FALSE
	fi
}

main "$@"
