#!/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_CONTAINER_MANAGER
#   DBX_CONTAINER_NAME
#	DBX_CONTAINER_RM_CUSTOM_HOME
#   DBX_NON_INTERACTIVE
#	DBX_SUDO_PROGRAM

# Dont' run this command as sudo.
if [ "$(id -u)" -eq 0 ]; then
	printf >&2 "Running %s as sudo is not supported.\n" "$(basename "${0}")"
	printf >&2 " try instead running:\n"
	printf >&2 "	%s --root %s\n" "$(basename "${0}")" "$*"
	exit 1
fi

# Defaults
container_manager="autodetect"
force=0
non_interactive=0
rootful=0
verbose=0
rm_home=0
distrobox_sudo_program="sudo"
version="1.4.2.1"

# Source configuration files, this is done in an hierarchy so local files have
# priority over system defaults
# leave priority to environment variables.
config_files="
	/usr/share/distrobox/distrobox.conf
	/usr/etc/distrobox/distrobox.conf
	/etc/distrobox/distrobox.conf
	${XDG_CONFIG_HOME:-"${HOME}/.config"}/distrobox/distrobox.conf
	${HOME}/.distroboxrc
"
for config_file in ${config_files}; do
	# Shellcheck will give error for sourcing a variable file as it cannot follow
	# it. We don't care so let's disable this linting for now.
	# shellcheck disable=SC1090
	[ -e "${config_file}" ] && . "${config_file}"
done
# Fixup non_interactive=[true|false], in case we find it in the config file(s)
[ "${non_interactive}" = "true" ] && non_interactive=1
[ "${non_interactive}" = "false" ] && non_interactive=0

[ -n "${DBX_CONTAINER_MANAGER}" ] && container_manager="${DBX_CONTAINER_MANAGER}"
[ -n "${DBX_CONTAINER_RM_CUSTOM_HOME}" ] && rm_home="${DBX_CONTAINER_RM_CUSTOM_HOME}"
[ -n "${DBX_NON_INTERACTIVE}" ] && non_interactive="${DBX_NON_INTERACTIVE}"
[ -n "${DBX_SUDO_PROGRAM}" ] && distrobox_sudo_program="${DBX_SUDO_PROGRAM}"

# Declare it AFTER config sourcing because we do not want a default name set for rm.
container_name=""
container_name_list=""

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

Usage:

	distrobox-rm [-f/--force] container-name [container-name1 container-name2 ...]

Options:

	--name/-n:		name for the distrobox
	--rm-home:		remove the mounted home if it differs from the host user's one
	--root/-r:		launch podman/docker with root privileges. Note that if you need root this is the preferred
				way over "sudo distrobox" (note: if using a program other than 'sudo' for root privileges is necessary,
				specify it through the DBX_SUDO_PROGRAM env variable, or 'distrobox_sudo_program' config variable)
	--help/-h:		show this message
	--verbose/-v:		show more verbosity
	--version/-V:		show version
EOF
}

# Parse arguments
while :; do
	case $1 in
		-h | --help)
			# Call a "show_help" function to display a synopsis, then exit.
			show_help
			exit 0
			;;
		-r | --root)
			shift
			rootful=1
			;;
		--rm-home)
			shift
			rm_home=1
			;;
		-v | --verbose)
			verbose=1
			shift
			;;
		-V | --version)
			printf "distrobox: %s\n" "${version}"
			exit 0
			;;
		-f | --force)
			force=1
			shift
			;;
		-Y | --yes)
			non_interactive=1
			shift
			;;
		--) # End of all options.
			shift
			break
			;;
		-*) # Invalid options.
			printf >&2 "ERROR: Invalid flag '%s'\n\n" "$1"
			show_help
			exit 1
			;;
		*) # Default case: If no more options then break out of the loop.
			# If we have a flagless option and container_name is not specified
			# then let's accept argument as container_name
			if [ -n "$1" ]; then
				container_name_list="${container_name_list} $1"
				shift
			else
				break
			fi
			;;
	esac
done

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

# We depend on a container manager let's be sure we have it
# First we use podman, else docker
case "${container_manager}" in
	autodetect)
		if command -v podman > /dev/null; then
			container_manager="podman"
		elif command -v docker > /dev/null; then
			container_manager="docker"
		fi
		;;
	podman)
		container_manager="podman"
		;;
	docker)
		container_manager="docker"
		;;
	*)
		printf >&2 "Invalid input %s.\n" "${container_manager}"
		printf >&2 "The available choices are: 'autodetect', 'podman', 'docker'\n"
		;;
esac

# Be sure we have a container manager to work with.
if ! command -v "${container_manager}" > /dev/null; then
	# Error: we need at least one between docker or podman.
	printf >&2 "Missing dependency: we need a container manager.\n"
	printf >&2 "Please install one of podman or docker.\n"
	printf >&2 "You can follow the documentation on:\n"
	printf >&2 "\tman distrobox-compatibility\n"
	printf >&2 "or:\n"
	printf >&2 "\thttps://github.com/89luca89/distrobox/blob/main/docs/compatibility.md\n"
	exit 127
fi
# add  verbose if -v is specified
if [ "${verbose}" -ne 0 ]; then
	container_manager="${container_manager} --log-level debug"
fi

# prepend sudo (or the specified sudo program) if we want podman or docker to be rootful
if [ "${rootful}" -ne 0 ]; then
	container_manager="${distrobox_sudo_program} ${container_manager}"
fi

# check if we have containers to delete
if [ -z "${container_name_list}" ]; then
	printf >&2 "Please specify a container name.\n"
	exit 1
fi

for container_name in ${container_name_list}; do
	# Inspect the container we're working with.
	container_status="$(${container_manager} inspect --type container \
		"${container_name}" --format '{{.State.Status}}')"
	container_exists="$?"
	# Does the container exist? check if inspect reported errors
	if [ "${container_exists}" -gt 0 ]; then
		# If not, prompt to create it first
		printf >&2 "Cannot find container %s, does it exist?\n" "${container_name}"
		exit 1
	fi

	# If the container is not already running, we need to start if first
	if [ "${container_status}" = "running" ]; then
		if [ "${force}" -ne 0 ]; then
			printf >&2 "Stopping container %s\n" "${container_name}"
			if ! ${container_manager} stop "${container_name}"; then
				printf >&2 "Could not stop container %s\n" "${container_name}"
				printf >&2 "Please stop container %s before deletion\n" "${container_name}"
				printf >&2 "Run:\n\t%s stop %s" "${container_manager}" "${container_name}"
				exit 1
			fi
		else
			printf >&2 "Please stop container %s before deletion\n" "${container_name}"
			printf >&2 "Run:\n\t%s stop %s\n" "${container_manager}" "${container_name}"
			printf >&2 'or use the "--force" flag'
			exit 1
		fi
	fi

	# Prompt for confirmation
	if [ "${non_interactive}" -eq 0 ] && [ "${force}" -eq 0 ]; then
		printf "Do you really want to delete %s? [Y/n]: " "${container_name}"
		read -r response
		response="${response:-"Y"}"
	else
		response="yes"
	fi

	# Retrieve container's HOME, and check if it's different from host's one. In
	# this case we prompt for deletion of the custom home.
	container_home=$(${container_manager} inspect "${container_name}" --format \
		'{{range .Config.Env}}{{if slice . 0 5 | eq "HOME="}}{{slice . 5}}{{end}}{{end}}')
	# Prompt for confirmation
	if [ "${non_interactive}" -eq 0 ] && [ "${container_home}" != "${HOME}" ] && [ "${rm_home}" -eq 0 ]; then
		printf "Do you want to remove custom home of container %s (%s)? [Y/n]: " "${container_name}" "${container_home}"
		read -r response_rm_home
		response_rm_home="${response_rm_home:-"Y"}"
	elif [ "${container_home}" != "${HOME}" ]; then
		if [ "${rm_home}" -eq 0 ]; then
			response_rm_home="N"
		else
			response_rm_home="Y"
		fi
	else
		response_rm_home="N"
	fi

	# Validate home response
	# Accept only y,Y,Yes,yes,n,N,No,no.
	case "${response_rm_home}" in
		y | Y | Yes | yes | YES)
			rm_home_local=1
			;;
		n | N | No | no | NO)
			rm_home_local=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

	# Accept only y,Y,Yes,yes,n,N,No,no.
	case "${response}" in
		y | Y | Yes | yes | YES)
			# We're going to delete the box, let's also delete the entry
			if [ "${rootful}" -eq 0 ]; then
				"$(dirname "$(realpath "${0}")")/distrobox-generate-entry" "${container_name}" --delete
			fi

			# Remove the container
			${container_manager} rm "${container_name}"

			# Remove custom home
			if [ "${rm_home_local}" -eq 1 ]; then
				rm -r "${container_home}"
				printf "Successfully removed %s\n" "${container_home}"
			fi
			;;
		n | N | No | no | NO)
			printf "Aborted.\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
done
