#!/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

# Print usage to stdout.
# Arguments:
#   None
# Outputs:
#   print usage with examples.
show_help() {
	cat << EOF
install --prefix ~/.local/podman

Options:
	--prefix/-P:		base bath where all files will be deployed (default ~/.local/)
	--help/-h:		show this message
	--remove/-R:		uninstall from prefix
	-v:			show more verbosity
EOF
}

# First thing first, chekc if we have all the dependencies.
printf >&2 "\033[1;31m Checking dependencies...\n\033[0m"
if [ ! -e /etc/subuid ] || [ ! -e /etc/subgid ]; then
	if ! command -v newuidmap > /dev/null; then
		echo "Rootless podman requires the presence of newuidmap and newgidmap, please install package 'uidmap'"
		echo "with your package manager."
		exit 1
	fi
	echo "Setting up subuid and subgid, needed for rootless podman..."
	echo "$(whoami):100000:65536" | sudo tee /etc/subuid | sudo tee /etc/subgid
fi

if [ "$(id -ru)" = 0 ]; then
	printf "ERROR: rootful install not supported in this mode.\n"
	exit 2
fi

verbose=0
remove=0
prefix="${HOME}/.local"

# Parse arguments
while :; do
	case $1 in
		-h | --help)
			# Call a "show_help" function to display a synopsis, then exit.
			show_help
			exit
			;;
		-v | --verbose)
			shift
			verbose=1
			;;
		-R | --remove)
			shift
			remove=1
			;;
		-P | --prefix)
			if [ -n "$2" ]; then
				prefix="$2"
				shift
				shift
			fi
			;;
		*) # Default case: If no more options then break out of the loop.
			break ;;
	esac
done

dest_path="${prefix}/podman"
conf_path="${HOME}/.config/"

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

export  PATH="${PATH}:${dest_path}/bin"

## Uninstall ###################################################################

if [ "${remove}" -ne 0 ]; then

	printf >&2 "\033[1;31m Resetting...\n\033[0m"
	"${dest_path}/bin/podman" system reset -f > /dev/null
	printf >&2 "\033[1;31m Removing...\n\033[0m"
	rm -r "${dest_path}" "${conf_path}/containers"
	printf >&2 "\033[1;31m Done.\n\033[0m"
	exit $?
fi

###############################################################################

## Get crun ###################################################################

CRUN_VERSION="1.6"
printf >&2 "\033[1;31m Fetching crun %s...\n\033[0m" "${CRUN_VERSION}"
# Download the binary to /tmp
curl -L \
	"https://github.com/containers/crun/releases/download/${CRUN_VERSION}/crun-${CRUN_VERSION}-linux-amd64" \
	-o "/tmp/crun"
chmod +x /tmp/crun

###############################################################################

## Get podman ###################################################################

PODMAN_VERSION="4.2.1"
printf >&2 "\033[1;31m Fetching podman %s...\n\033[0m" "${PODMAN_VERSION}"
# Using static podman bulds semplifies our lifes! Thanks to the wonderful project
#   https://github.com/mgoltzsche/podman-static
# All credits to @mgoltzsche for the builds.
# Download and unpack the tar in /tmp
curl -L \
	"https://github.com/mgoltzsche/podman-static/releases/download/v${PODMAN_VERSION}/podman-linux-amd64.tar.gz" \
	-o /tmp/podman-linux-amd64.tar.gz
printf >&2 "\033[1;31m Unpacking Podman...\n\033[0m"
tar xf /tmp/podman-linux-amd64.tar.gz -C /tmp/

###############################################################################

printf >&2 "\033[1;31m Copying in %s...\n\033[0m" "${dest_path}"
# Copy default config files in there
mkdir -p "${conf_path}" "${dest_path}"
cp -r /tmp/podman-linux-amd64/usr/local/bin "${dest_path}"
cp -r /tmp/podman-linux-amd64/usr/local/lib "${dest_path}"
cp -r /tmp/podman-linux-amd64/etc/containers "${conf_path}"
mv /tmp/crun "${dest_path}/bin/crun"

printf >&2 "\033[1;31m Configuring...\n\033[0m"
# We need to tell podman to use those costom directories in order to make
# it work from custom directories
cat << EOF > "${conf_path}/containers/containers.conf"
# See https://github.com/containers/common/blob/master/pkg/config/containers.conf
[engine]
# can be croupfs, systemd
cgroup_manager = "systemd"
# can be file, journald
events_logger="file"
exit_command_delay = 10
# can be runc, crun
runtime = "crun"
stop_timeout = 5
conmon_path=[ "${dest_path}/lib/podman/conmon" ]
helper_binaries_dir = [ "${dest_path}/lib/podman" ]
static_dir = "${dest_path}/share/podman/libpod"
volume_path = "${dest_path}/share/podman/volume"
[engine.runtimes]
crun = [ "${dest_path}/bin/crun" ]
runc = [ "${dest_path}/bin/runc" ]
[network]
cni_plugin_dirs = [ "${dest_path}/lib/cni" ]
EOF

# Same for mouning programs
sed -i "s|/var|${dest_path}|g" "${conf_path}/containers/storage.conf"
sed -i "s|mount_program =.*|mount_program = \"${dest_path}/bin/fuse-overlayfs\"|g" \
	"${conf_path}/containers/storage.conf"

printf >&2 "\033[1;31m Cleaning up...\n\033[0m"
# Cleanup
rm -rf /tmp/podman-linux-amd64/ /tmp/podman-linux-amd64.tar.gz /tmp/crun

printf >&2 "\033[1;31m Migrating...\n\033[0m"

"${dest_path}/bin/podman" system migrate

printf >&2 "Successfully installed to %s.\n" "${dest_path}"
printf >&2 "Be sure that %s is in your \$PATH environment variable for it to work.\n" "${dest_path}/bin"
