#!/bin/sh
# SPDX-License-Identifier: GPL-3.0-only
#
# This file is part of the distrobox project:
#    https://github.com/89luca89/distrobox
#
# Copyright (C) 2022 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/>.

# Defaults
host_command=""
non_interactive=0
# If we're in a non-interactive shell, let's act accordingly
if [ ! -t 1 ]; then
	non_interactive=1
fi
distrobox_host_exec_default_command="${SHELL:-/bin/sh}"
host_spawn_version="1.2.1"
verbose=0
version="1.4.2.1"

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

Usage:

	distrobox-host-exec [command [arguments]]
	distrobox-host-exec ls
	distrobox-host-exec bash -l
	distrobox-host-exec flatpak run org.mozilla.firefox
	distrobox-host-exec podman ps -a


Options:

	--help/-h:		show this message
	--verbose/-v:		show more verbosity
	--version/-V:		show version
    --yes/-Y:      Automatically answer yes to prompt:
                                host-spawn will be installed on the guest system
                                if host-spawn is not detected.
                                This behaviour is default when running in a non-interactive shell.
EOF
}

# If we're a symlink to a command, use that as command to exec, and skip arg parsing.
if [ "$(basename "${0}")" != "distrobox-host-exec" ]; then
	host_command="$(basename "${0}")"
fi
# Parse arguments
if [ -z "${host_command}" ]; then
	# Skip argument parsing if we're a symlink
	while :; do
		case $1 in
			-h | --help)
				# Call a "show_help" function to display a synopsis, then exit.
				show_help
				exit 0
				;;
			-v | --verbose)
				verbose=1
				shift
				;;
			-V | --version)
				printf "distrobox: %s\n" "${version}"
				exit 0
				;;
			-Y | --yes)
				non_interactive=1
				shift
				;;
			--) # End of all options.
				shift
				;;
			-*) # Invalid options.
				printf >&2 "ERROR: Invalid flag '%s'\n\n" "$1"
				show_help
				exit 1
				;;
			*)
				if [ -n "$1" ]; then
					host_command=$1
					shift
				fi
				break
				;;
		esac
	done
fi

set -o errexit
set -o nounset
# set verbosity
if [ "${verbose}" -ne 0 ]; then
	set -o xtrace
fi

# Check we're running inside a container and not on the host
if [ ! -f /run/.containerenv ] && [ ! -f /.dockerenv ]; then
	printf >&2 "You must run %s inside a container!\n" " $(basename "$0")"
	exit 126
fi

if [ -z "${host_command}" ]; then
	host_command="${distrobox_host_exec_default_command}"
fi

# Setup host-spawn as a way to execute commands back on the host
if  ! command -v host-spawn > /dev/null ||
	[ "$(host-spawn --version)" != "${host_spawn_version}" ]; then

	# if non-interactive flag flag hasn't been set
	if [ "${non_interactive}" -eq 0 ]; then
		# Prompt to download it.
		printf "Warning: host-spawn not found or version is too old!\n"
		printf "Do you want to install host-spawn utility? [Y/n] "
		read -r response
		response=${response:-"Y"}
	else
		response="yes"
	fi
	# Accept only y,Y,Yes,yes,n,N,No,no.
	case "${response}" in
		y | Y | Yes | yes | YES)
			# Download matching version with current distrobox
			if ! curl -L \
				"https://github.com/1player/host-spawn/releases/download/${host_spawn_version}/host-spawn-$(uname -m)" \
				-o /tmp/host-spawn; then

				printf "Error: Cannot download host-spawn\n"
				exit 1
			fi
			if [ -e /tmp/host-spawn ]; then
				sudo mv /tmp/host-spawn /usr/bin/
				sudo chmod +x /usr/bin/host-spawn
			fi
			;;
		n | N | No | no | NO)
			printf "Installation aborted, please install host-spawn.\n"
			exit 0
			;;
		*) # Default case: If no more options then break out of the loop.
			printf >&2 "Invalid input.\n"
			printf >&2 "The available choices are: y,Y,Yes,yes,YES or n,N,No,no,NO.\nExiting.\n"
			exit 1
			;;
	esac

fi

###
# This workaround is needed because of a bug in gio (used by xdg-open) where
# a race condition happens when allocating a pty, leading to the command
# being killed before having time to be executed.
#
# https://gitlab.gnome.org/GNOME/glib/-/issues/2695
# https://github.com/1player/host-spawn/issues/7
#
# As an (ugly) workaround, we will not allocate a pty for those commands.
###
# Also, we don't initialize a pty, if we're not in a tty.
if  [ "$(basename "${host_command}")" = "xdg-open" ] ||
	[ "$(basename "${host_command}")" = "gio" ] ||
	[ ! -t 1 ]; then

	host-spawn --no-pty "${host_command}" "$@"
	# Exit here, we don't continue execution
	exit $?
fi

host-spawn  "${host_command}" "$@"
# Exit here, we don't continue execution
exit  $?
