#!/usr/bin/env bash
# CreateWorkDir
# Creates a dir structure for working with Parabola packages

# Copyright (C) 2010-2011 Nicolás Reynolds <fauno@parabola.nu>
# Copyright (C) 2011 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/>.

set -euE

. "$(librelib messages)"
. "$(librelib conf)"

usage() {
	print 'Usage: %s [OPTIONS]' "${0##*/}"
	print 'Initialize a ~/packages/ working directory.'
	echo
	prose 'The location my be configured with libretools.conf:WORKDIR.'
	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 && $# -gt 0 ]]; then
			gnuerror 'Extra arguments: %s' "$*"
			mode=errusage
		fi
	fi
	case "$mode" in
		errusage)
			print "Try '%s --help' for more information." "${0##*/}" >&2
			exit $EXIT_INVALIDARGUMENT
			;;
		usage)
			usage
			exit $EXIT_SUCCESS
			;;
		run) : ;;
		*) panic 'invalid mode: %q' "$mode" ;;
	esac

	load_conf libretools.conf WORKDIR ABSLIBRERECV ABSLIBRESEND

	trap 'error "Aborting..."' EXIT

	msg "Creating WORKDIR at %s..." "$WORKDIR"
	mkdir -p "$WORKDIR"

	msg "Creating staging directory in WORKDIR..."
	mkdir -p "$WORKDIR/staging"

	cmd=(gitget -f -p "$ABSLIBRESEND" checkout "$ABSLIBRERECV" "$WORKDIR/abslibre")
	if ! "${cmd[@]}"; then
		error "Could not clone ABSLibre"
		plain "Try running this command:"
		echo
		printf '%q ' "${cmd[@]}"
		echo
		exit $EXIT_FAILURE
	fi

	msg "Finished, your packaging directory tree looks like this now:"
	ls --color=auto "${WORKDIR}"/*

	trap -- EXIT
}

main "$@"
