#!/bin/sh
# SPDX-License-Identifier: GPL-3.0-only
#
# This file is part of the distrobox project:
#    https://github.com/89luca89/distrobox
#
# Copyright (C) 2021 distrobox contributors
#
# distrobox is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License version 3
# as published by the Free Software Foundation.
#
# distrobox 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 distrobox; if not, see <http://www.gnu.org/licenses/>.

# POSIX
# Optional env variables:
#	DBX_DEFAULT_COMMAND

default_command="enter"
[ -n "${DBX_DEFAULT_COMMAND}" ] && default_command="${DBX_DEFAULT_COMMAND}"

trap '[ "$?" -ne 0 ] && printf "\nAn error occurred\n"' EXIT

version="1.3.1"

# Print usage to stdout.
# Arguments:
#   None
# Outputs:
#   print usage with examples.
show_help() {
	cat << EOF
distrobox version: ${version}

Choose one of the available commands:
	create
	enter
	list
	stop
	rm
	version
EOF
}

# Handle 'help' here, before setting 'errexit', so we have a chance
# to show our help if the man command is there but fails.
if [ "$1" = "help" ] || [ "$1" = "--help" ] || [ "$1" = "-h" ]; then
	if command -v man > /dev/null; then
		man distrobox && exit 0
	fi
	show_help
	exit 0
fi

set -o errexit
set -o nounset

distrobox_path="$(dirname "${0}")"
if [ $# -eq 0 ]; then
	printf "No command specified. Assuming: distrobox-%s\n" "${default_command}"
	distrobox_command="${default_command}"
else
	distrobox_command="${1}"
	shift
fi

# Simple wrapper to the distrobox utilities.
# We just detect the 1st argument and launch the matching distrobox utility.
case "${distrobox_command}" in
	create)
		"${distrobox_path}"/distrobox-create "$@"
		;;
	enter)
		"${distrobox_path}"/distrobox-enter "$@"
		;;
	list)
		"${distrobox_path}"/distrobox-list "$@"
		;;
	stop)
		"${distrobox_path}"/distrobox-stop "$@"
		;;
	rm)
		"${distrobox_path}"/distrobox-rm "$@"
		;;
	-V | --version | version)
		printf "distrobox: %s\n" "${version}"
		exit 0
		;;
	*) # Default case: If no more options then break out of the loop.
		printf >&2 "Error: invalid command\n"
		show_help
		exit 1
		;;
esac
