#!/bin/sh
#
# kas - setup tool for bitbake based projects
#
# Copyright (c) Siemens AG, 2017-2026
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.

do_enable_qemu_binfmts()
{
	if ! [ -f /proc/sys/fs/binfmt_misc/status ]; then
		sudo mount -t binfmt_misc null /proc/sys/fs/binfmt_misc || return
	fi
	for CONF in /usr/lib/binfmt.d/qemu-*.conf; do
		if ! [ -f /proc/sys/fs/binfmt_misc/"$(basename "${CONF%%.conf}")" ]; then
			sudo sh -c "cat '$CONF' > /proc/sys/fs/binfmt_misc/register" || return
		fi
	done
}

enable_qemu_binfmts()
{
	if ! do_enable_qemu_binfmts; then
		echo "kas-container: failed to set up binfmt_misc" >&2
		exit 1
	fi
}

# For rootless nesting of the uid_ns, we need to provide a list of sub
# uids/gids which can be used in the sub namespace. As each id in the
# sub namespace must be mappable into the parent namespace, we need to
# compute the mapping based on the layout of the parent: Podman maps
# to an intermediate namespace, hence giving us a user-id map we
# actually can use for further splitting. Docker maps directly, hence
# we need to compute the number of sub ids we can use (which have a
# mapping in the parent ns)
#
# Note, that the default range (65k) does NOT allow to map nobody/nogroup,
# in the sub-namespace, as this usually is id 65k-1 and we loose at least
# one id per nesting. If we get a larger range, we just map as much as
# we can and by that make nobody/nogroup usable.
# See man user_namespaces for details.
setup_userns_mappings()
{
	UID_ROW=$(sort -r /proc/self/uid_map | head -1)
	UID_OUTER=$(printf '%s' "$UID_ROW" | awk '{print $1}')
	UID_INNER=$(printf '%s' "$UID_ROW" | awk '{print $2}')
	UID_COUNT=$(printf '%s' "$UID_ROW" | awk '{print $3}')
	GID_ROW=$(sort -r /proc/self/gid_map | head -1)
	GID_OUTER=$(printf '%s' "$GID_ROW" | awk '{print $1}')
	GID_INNER=$(printf '%s' "$GID_ROW" | awk '{print $2}')
	GID_COUNT=$(printf '%s' "$GID_ROW" | awk '{print $3}')

	# docker (direct mapping)
	if [ "$UID_OUTER" = "1" ]; then
		UID_INNER="$(($(id -u builder) + 1))"
		[ "$UID_INNER" -lt "$UID_COUNT" ] && \
			UID_COUNT="$((UID_COUNT - UID_INNER))"
	fi
	if [ "$GID_OUTER" = "1" ]; then
		GID_INNER="$(($(id -g builder) + 1))"
		[ "$GID_INNER" -lt "$GID_COUNT" ] && \
			GID_COUNT="$((GID_COUNT - GID_INNER))"
	fi

	echo "builder:${UID_INNER}:${UID_COUNT}" | sudo tee /etc/subuid > /dev/null
	echo "builder:${GID_INNER}:${GID_COUNT}" | sudo tee /etc/subgid > /dev/null
}

# kas-isar: enable_qemu_binfmts

chown_managed_dirs()
{
	for DIR in /build /work /sstate /downloads /repo-ref; do
		if [ -d "$DIR" ]; then
			chown "$1":"$2" "$DIR"
		fi
	done

	# SSH Directory Permissions
	if [ -d "/builder/.ssh" ]; then
		chown -R "$1":"$2" "/builder/.ssh"
	fi
}

restore_managed_dirs_owner()
{
	chown_managed_dirs 0 0
}

if mount | grep -q "on / type aufs"; then
    cat <<EOF >&2
WARNING: Generation of wic images will fail!

Your docker host setup uses broken aufs as storage driver. Adjust the docker
configuration to use a different driver (overlay, overlay2, devicemapper). You
may also need to update the host distribution (e.g. Debian Jessie -> Stretch).

EOF
fi

# if the container is started from a not supported terminal, fallback to xterm
if [ -n "$TERM" ]; then
	infocmp "$TERM" > /dev/null 2>&1 || TERM=xterm
fi

if [ -z "$USER_ID" ] && [ -n "$CI_PROJECT_DIR" ]; then
	# Work around for gitlab-runner not aligning checked out repo ownership
	# with our builder user. We handle that internally in kas, but we
	# need the exception here as well for git calls outside of kas.
	sudo git config --system safe.directory "$CI_PROJECT_DIR"

	# Account for externally specified git clone path
	if [ -n "$GIT_CLONE_PATH" ]; then
		sudo git config --system --add safe.directory "$GIT_CLONE_PATH"
	fi
fi
if [ -z "$USER_ID" ] || [ "$USER_ID" = 0 ]; then
	# Not a kas-container call, or we shall run everything as root
	GOSU=""
else
	GROUP_ID=${GROUP_ID:-$(id -g)}

	groupmod -o --gid "$GROUP_ID" builder
	usermod -o --uid "$USER_ID" --gid "$GROUP_ID" builder >/dev/null
	chown -R "$USER_ID":"$GROUP_ID" /builder
	# copy host SSH config into home of builder
	if [ -d /var/kas/userdata/.ssh ]; then
		cp -a /var/kas/userdata/.ssh /builder/
	fi
	# adjust timezone to host
	if [ -n "${KAS_HOST_TZ}" ] && [ -f "/usr/share/zoneinfo/${KAS_HOST_TZ}" ]; then
		echo "${KAS_HOST_TZ}" > /etc/timezone
		ln -sf "/usr/share/zoneinfo/${KAS_HOST_TZ}" /etc/localtime
	fi

	GOSU="gosu builder"
fi
# after all uid / gid changes are done, setup the namespace mappings
# kas-isar: setup_userns_mappings

# kas-container on rootless docker workaround
if [ -n "$USER_ID" ] && [ "$USER_ID" -ne 0 ] && \
   [ "$KAS_DOCKER_ROOTLESS" = "1" ] && [ "$(stat -c %u /repo)" -eq 0 ]; then
	# Docker rootless does not support keeping the user namespace
	# (podman option --userns=keep-id). By that, the bind mounts
	# are owned by root.
	git config --system safe.directory /repo
	chown_managed_dirs "$USER_ID" "$GROUP_ID"

	# Copy userdata to a writable location so we can chown it.
	if [ -d "/var/kas/userdata" ]; then
		mv /var/kas/userdata /var/kas/userdata.orig
		cp -r /var/kas/userdata.orig /var/kas/userdata
		chown -R "$USER_ID":"$GROUP_ID" /var/kas/userdata
	fi
fi

if [ "$PWD" = / ]; then
	cd /builder || exit 1
fi

if [ -n "$1" ]; then
	case "$1" in
	build|checkout|clean*|diff|dump|for-all-repos|lock|menu|purge|shell|-*)
		# We must restore the dir owner after every kas invocation.
		# This is cheap as only the top-level dirs are changed (non recursive).
		if [ "$KAS_DOCKER_ROOTLESS" = "1" ]; then
			trap restore_managed_dirs_owner EXIT INT TERM
			$GOSU kas "$@"
		else
			# SC2086: Double quote to prevent globbing and word splitting.
			# shellcheck disable=2086
			exec $GOSU kas "$@"
		fi
		;;
	*)
		if [ -n "$USER_ID" ]; then
			echo "kas-container: this container does not support \"kas $1\"" >&2
			exit 1
		fi
		# SC2086: Double quote to prevent globbing and word splitting.
		# shellcheck disable=2086
		exec $GOSU "$@"
		;;
	esac
else
	# SC2086: Double quote to prevent globbing and word splitting.
	# shellcheck disable=2086
	exec $GOSU bash
fi
