#!/bin/bash

set -eu

if [ ${#} -lt 2 ]; then
	echo "usage: ${0} <mountpoint> <architecture> [entrypoint...]" >&2
	exit 1
fi

if [ $(id -u) -ne 0 ]; then
	echo "FATAL: must be root..." >&2
	exit 1
fi

read srcdir < <( readlink -e "${1}" )
arch="${2}"
shift 2

qemu_static_ref="/usr/bin/qemu-${arch}-static"

if [ ! -x "${qemu_static_ref}" ]; then
	echo "FATAL: ${qemu_static_ref} is missing..." >&2
	echo "       try installing qemu-user-static and binfmt-support" >&2
	exit 1
fi

qemu_static_src="${srcdir}${qemu_static_ref%/*}"
if [ ! -d "${qemu_static_src}" ]; then
	echo "FATAL: ${qemu_static_src} is missing..." >&2
	echo "       don't know where to place ${qemu_static_ref##*/}..." >&2
	exit 1
fi

mount_list=()
mount_record() {
	fs_type="${1}"; shift
	fs_target="${1}"; shift

	[ ${#} -eq 0 ]

	mount_list+=("${fs_target}")
	mount -t "${fs_type}" "${fs_type}" "${fs_target}"
}

cleanup() {
	if [ ! -z ${chroot_done:+x} ]; then
		echo "--- Welcome back... ---"
		cd /
	fi
	for i in $(seq $(( ${#mount_list[@]} - 1 )) -1 0); do
		mp="${mount_list[${i}]}"
		[ -d "${mp}" ] || continue
		mountpoint -q "${mp}" || continue
		umount "${mp}"
	done
	if [ $(stat -c '%s' "${tmpdir}") -le 2 ]; then
		[ ! -z ${tmpdir:+x} ] && rm -rf "${tmpdir}"
	else
		echo "WARNING: tmpdir \"${tmpdir}\" is not empty..." >&2
	fi
}
trap cleanup EXIT

read tmpdir < <( mktemp -d -p "${PWD}" ".stepin.XXXXXX" )
echo "${tmpdir}"

tmproot="${tmpdir}/dstdir"

mount_record tmpfs "${tmpdir}"

mkdir \
	"${tmpdir}/workdir" \
	"${tmpdir}/upperdir" \
	"${tmproot}"

mount_list+=("${tmproot}")
mount -t overlay overlay \
	-o lowerdir="${srcdir}" \
	-o workdir="${tmpdir}/workdir" \
	-o upperdir="${tmpdir}/upperdir" \
	"${tmproot}"

mount_record devtmpfs "${tmproot}/dev"
mount_record devpts   "${tmproot}/dev/pts"
mount_record tmpfs    "${tmproot}/dev/shm"
mount_record proc     "${tmproot}/proc"
mount_record sysfs    "${tmproot}/sys"
mount_record tmpfs    "${tmproot}/tmp"

cp "${qemu_static_ref}" "${tmproot}${qemu_static_ref}"

if [ ${#} -gt 0 ]; then
	cmd=( "${@}" )
elif [ -e "${tmproot}/bin/bash" ]; then
	cmd=( "/bin/bash" )
elif [ -e "${tmproot}/bin/sh" ]; then
	cmd=( "/bin/sh" )
else
	echo "FATAL: cannot find suitable entrypoint..." >&2
	exit 1
fi

echo "--- You're now in Narnia! ---"
chroot_done=1
chroot "${tmproot}" "${cmd[@]}"
exit $?
