#!/bin/sh
# fake/schroot-1.6.10-3 -- emulate how schroot/1.6.10-3 would chroot.
# It bind-mounts /dev/pts and maybe /dev from the host system.
# (There is of course a lot more that it does, but these are the parts that
# affect pty users like script(1).)
#
# Copyright © 2017 Simon McVittie
# SPDX-License-Identifier: MIT
# (see debian/copyright)

set -e

# /etc/schroot/default/fstab
bind_dev=yes

while true; do
	case "$1" in
		(--sbuild)
			shift
			# /etc/schroot/sbuild/fstab
			bind_dev=no
			;;
		(*)
			break
	esac
done

chroot="$1"
shift
if test -z "$chroot" || test -z "$1"; then
	echo "Usage: $0 CHROOT COMMAND...">&2
	exit 2
fi

[ "$bind_dev" = no ] || mount --bind /dev "$chroot/dev"
mount --bind /dev/pts "$chroot/dev/pts"
mount --bind /dev/ptmx "$chroot/dev/ptmx"

ls -l "$chroot/dev/ptmx" | sed -e 's/^/# fake-schroot: /' >&2
ls -l "$chroot/dev/pts/ptmx" | sed -e 's/^/# fake-schroot: /' >&2

e=0
chroot "$chroot" "$@" || e=$?

umount "$chroot/dev/pts"
umount "$chroot/dev/ptmx"
[ "$bind_dev" = no ] || umount "$chroot/dev"

exit "$e"
