#!/bin/sh

#
# Copyright 2023-2024 Peter Wienemann <fossdev@posteo.de>
#
# SPDX-License-Identifier: Apache-2.0
#
# Test whether the examples in the Charliecloud tutorial work
# (see https://hpc.github.io/charliecloud/tutorial.html)
#

set -eu

check_kernel () {
	unpriv_userns=-1
	if [ -r /proc/sys/kernel/unprivileged_userns_clone ]; then
		unpriv_userns=$(cat /proc/sys/kernel/unprivileged_userns_clone)
		if [ "$unpriv_userns" -eq 0 ]; then
			echo "Unprivileged user namespaces are disabled in kernel" > /dev/stderr
			exit 2
		fi
	else
		echo "Cannot access unprivileged user namespace settings in kernel" > /dev/stderr
		exit 1
	fi
}

check_build () {
	# The builder to use
	BUILDER="$1"
	# The number of retries in case anything goes wrong during the image build
	NUM_RETRIES="$2"
	# The number of seconds to wait before retrying the build
	DELAY="$3"
	cd /usr/share/doc/charliecloud/examples/hello
	case ${BUILDER} in

		ch-image)
			# Use --quiet option to suppress
			# FAIL stderr: initializing storage directory: v5 /var/tmp/root.ch
			for I in $(seq 1 ${NUM_RETRIES}); do ch-image build --quiet . && break || sleep ${DELAY}; done
			;;

		*)
			echo "Unknown builder" > /dev/stderr
			exit 1
			;;

	esac
}

check_convert () {
	FORMAT="$1"
	ch-convert --quiet hello /var/tmp/hello.${FORMAT}
}

check_run () {
	FORMAT="$1"
	ch-run --quiet /var/tmp/hello.${FORMAT} -- echo "I'm in a container"
}


check_kernel

# Address the issue described in
# https://stackoverflow.com/questions/38386809/docker-error-http-408-response-body-invalid-character-looking-for-beginnin
IFACE=$(ip -j addr | jq -r '.[] | select(.operstate == "UP") | .ifname')
ip link set dev "${IFACE}" mtu 1400

for BUILDER in ch-image; do
	echo "Testing builder ${BUILDER}:"
	check_build ${BUILDER} 5 60
done

for FORMAT in dir squash tar.gz; do
	echo "Testing ch-convert for format ${FORMAT}:"
	check_convert ${FORMAT}
done

# Skip squash format since FUSE mounts do not work in salsa runners
for FORMAT in dir; do
	echo "Testing ch-run for format ${FORMAT}:"
	check_run ${FORMAT}
done
