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

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

_DEVTOOLS_LIBRARY_DIR=${_DEVTOOLS_LIBRARY_DIR:-@pkgdatadir@}
# shellcheck source=src/lib/api/gitlab.sh
source "${_DEVTOOLS_LIBRARY_DIR}"/lib/api/gitlab.sh

set -e

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

		Star a package's GitLab project.

		If no package is specified, the current directory's package will be used.
		Multiple packages can be specified to star multiple projects at once.

		Every usage of the star command must be authenticated. Consult the
		'pkgctl auth' command to authenticate with GitLab or view the
		authentication status.

		OPTIONS
		    -h, --help     Show this help text
		    -u, --unstar   Remove star from the project instead

		EXAMPLES
		    $ ${COMMAND} pacman
		    $ ${COMMAND} --unstar pacman
		    $ ${COMMAND} libfoo libbar
_EOF_
}

pkgctl_star() {
	if (( $# == 0 )) && [[ ! -f PKGBUILD ]]; then
		pkgctl_star_usage
		exit 1
	fi

	# Check authentication
	if [[ -z ${GITLAB_TOKEN} ]]; then
		die "GitLab authentication required. Run 'pkgctl auth login' first"
	fi

	local unstar=0
	local pkgbases=()

	# option checking
	while (( $# )); do
		case $1 in
			-h|--help)
				pkgctl_star_usage
				exit 0
				;;
			-u|--unstar)
				unstar=1
				shift
				;;
			-*)
				die "invalid argument: %s" "$1"
				;;
			*)
				pkgbases+=("$1")
				shift
				;;
		esac
	done

	# Use current directory if no packages specified
	if (( ${#pkgbases[@]} == 0 )); then
		pkgbases=("$(basename "$PWD")")
	fi

	# Star/unstar each package
	for pkgbase in "${pkgbases[@]}"; do
		if (( unstar )); then
			msg "Unstarring %s..." "${pkgbase}"
			gitlab_api_unstar "${pkgbase}"
		else
			msg "Starring %s..." "${pkgbase}"
			gitlab_api_star "${pkgbase}"
		fi
	done
}
