#!/usr/bin/env bash

# Copyright (C) 2012-2013, 2017, 2024 Luke T. Shumaker <lukeshu@parabola.nu>
#
# License: GNU GPLv2+
#
# 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 2 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/>.

export TEXTDOMAIN='gitget'
. "$(librelib messages)"

usage() {
	print 'Usage: %s <REPO> <REF> <DIR>' "${0##*/}"
	print '   or: %s {-h|--help}' "${0##*/}"
	print 'A compatibility wrapper around `gitget checkout`.'
	echo
	prose "This exists because gitget used to be called libregit, and took
	       the arguments in this format, and I'm sure there are a few
	       scripts floating around that use it."
	echo
	prose "Clones or pulls from the git URL '<REPO>', and checks out the git
	       ref '<REF>' to the directory '<DIR>'."
	echo
	print "Options:"
	flag \
		'-h, --help' 'Show this message'
}

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 3 ]]; then
			gnuerror 'expected 3 non-flag 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

	repo=$1
	ref=$2
	dir=$3

	gitget checkout "${repo}#ref=${ref}" "${dir}"
}

main "$@"
