#!/usr/bin/env bash
# Copyright (C) 2013-2015, 2017-2018, 2024  Luke T. Shumaker <lukeshu@parabola.nu>
#
# SPDX-License-Identifier: GPL-2.0-or-later
#
# This file is part of Parabola Libretools.
#
# Libretools 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 2 of the License, or
# (at your option) any later version.
#
# Libretools 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 this program.  If not, see <http://www.gnu.org/licenses/>.
{
	set -e

	if [[ $# == 0 ]]; then
		echo 'You need to run testenv with arguments!' >&2
		exit 1
	fi

	# Set up the working directory, and add the hook to clean it up
	export TMPDIR="$(mktemp --tmpdir -d libretools-test.XXXXXXXXXX)"
	cleanup() {
		set +e
		# coordinate this with ./lib/common.bash
		if [[ -f "$TMPDIR/.used-sudo" ]] && [[ -d "$TMPDIR/chroots" ]]; then
			if [[ "$(stat -f -c %T "$TMPDIR/chroots")" == btrfs ]]; then
				sudo find "$TMPDIR/chroots" -depth -inum 256 -exec \
					btrfs subvolume delete {} \; &>/dev/null
			fi
			sudo rm -rf -- "$TMPDIR/chroots"
		fi
		rm -rf -- "$TMPDIR"
	}
	trap cleanup EXIT

	# Set up the install to work with
	destdir=$TMPDIR/destdir

	old_pwd="$(pwd)"
	if [[ -f $0 ]]; then
		cd "${0%/*}"
	fi
	if ! make -C .. install prefix=/usr sysconfdir=/etc DESTDIR="$destdir" &>"$TMPDIR/make-output"; then
		echo 'error creating local install, cannot run tests' >&2
		cat "$TMPDIR/make-output"
		exit 1
	fi
	cd "$old_pwd"

	# Set up the environment
	export PATH="$destdir/usr/bin:$PATH"
	export TEXTDOMAINDIR="$destdir/usr/share/locale"
	export LIBRETOOLS_LIBRARY_PATH="$destdir/usr/lib/libretools"
	export _librelib_conf_sh_sysconfdir="$destdir/etc"
	export _librelib_conf_sh_pkgconfdir="$destdir/etc/libretools.d"
	sed -i 's,/usr/bin/librefetch,$(type -p librefetch),' \
		"${_librelib_conf_sh_sysconfdir}/makepkg.conf.d/librefetch.conf"

	# Hack to respect our variables in sudo
	install -Dm755 /dev/stdin "$destdir/usr/bin/testsudo" <<-eot
		#!/bin/bash
		touch ${TMPDIR@Q}/.used-sudo
		vars=(
			TMPDIR
			GNUPGHOME XDG_CACHE_HOME XDG_CONFIG_HOME
			PATH LIBRETOOLS_LIBRARY_PATH _librelib_conf_sh_sysconfdir _librelib_conf_sh_pkgconfdir
			GPGKEY
		)
		env=()
		for var in "\${vars[@]}"; do
			env+=("\$var=\${!var}")
		done
		# The /etc/sudoers policy may do funny things with the
		# env-vars we set, so use the separate "env" command
		# instead.  This means we have to split the flags from the main
		# arg-list.
		flags=()
		OPTIND=1
		while getopts 'u:' arg; do
			case "\$arg" in
				u) flags+=(-u "\$OPTARG") ;;
				'?') : ;;
			esac
		done
		shift \$((OPTIND - 1))
		sudo "\${flags[@]}" -- env "\${env[@]}" "\$@"
	eot
	# Hack to work around GnuPG being stupid with locating gpg-agent's socket
	install -Dm755 /dev/stdin "$destdir/usr/bin/gpg" <<-'eot'
		#!/bin/bash
		export GNUPGHOME="${GNUPGHOME:-$HOME/.gnupg}"
		if [[ $GNUPGHOME == "$HOME/.gnupg" ]]; then
			export HOME=/var/empty
		fi
		exec /usr/bin/gpg "$@"
	eot
	install -Dm755 /dev/stdin "$destdir/usr/bin/gpg-connect-agent" <<-'eot'
		#!/bin/bash
		export GNUPGHOME="${GNUPGHOME:-$HOME/.gnupg}"
		if [[ $GNUPGHOME == "$HOME/.gnupg" ]]; then
			export HOME=/var/empty
		fi
		exec /usr/bin/gpg-connect-agent "$@"
	eot
	# Hack to work around ssh ignoring HOME and instead looking the homedir in NSS
	install -Dm755 /dev/stdin "$destdir/usr/bin/ssh" <<-'eot'
		#!/bin/bash
		vars=(
			TMPDIR
			_HOME GNUPGHOME XDG_CACHE_HOME XDG_CONFIG_HOME
			_PATH LIBRETOOLS_LIBRARY_PATH _librelib_conf_sh_sysconfdir _librelib_conf_sh_pkgconfdir
			GPGKEY
		)
		export _HOME="$HOME"
		export _PATH="$PATH"
		exec /usr/bin/ssh \
			-o SendEnv="${vars[*]}" \
			-o IdentityFile="$HOME/.ssh/id_rsa" \
			-o UserKnownHostsFile="$HOME/.ssh/known_hosts" \
			-F "$HOME/.ssh/config" \
			"$@"
	eot

	# Run the tests
	command -- "$@"
}
