about summary refs log tree commit diff
path: root/xchroot
blob: 2c68623f928ec137494b879d4cb1c076283bc11f (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
#!/bin/sh -e
# xchroot DIR [CMD...] - chroot into a Void (or other Linux) installation

fail() {
	printf '%s\n' "$1" 1>&2
	exit 1
}

if [ "$(id -u)" -ne 0 ]; then
	fail 'xchroot needs to run as root'
fi

case "$1" in
	/*) CHROOT=$1; shift;;
	*) fail 'no absolute chroot dir given';;
esac

[ -d "$CHROOT" ] || fail 'not a directory'
[ -d "$CHROOT/dev" ] || fail 'no /dev in chroot'
[ -d "$CHROOT/proc" ] || fail 'no /proc in chroot'
[ -d "$CHROOT/sys" ] || fail 'no /sys in chroot'

mount --rbind /dev "$CHROOT/dev"
mount --rbind /proc "$CHROOT/proc"
mount --rbind /sys "$CHROOT/sys"
touch "$CHROOT/etc/resolv.conf"
mount --bind /etc/resolv.conf "$CHROOT/etc/resolv.conf"

cleanup() {
	umount -R "$CHROOT/dev" "$CHROOT/etc/resolv.conf" "$CHROOT/proc" "$CHROOT/sys"
}

trap cleanup EXIT INT

if [ -f "$CHROOT/$SHELL" ]; then
	INNER_SHELL="$SHELL"
elif [ -f "$CHROOT/bin/bash" ]; then
	INNER_SHELL="/bin/bash"
else
	INNER_SHELL="/bin/sh"
fi

printf "\033[1m=> Entering chroot $CHROOT\033[m\n"
export PS1="[xchroot $CHROOT] $PS1"
if chroot "$CHROOT" ${@:-$INNER_SHELL}; then
	printf "\033[1m=> Exited chroot $CHROOT\033[m\n"
else
	printf "\033[1m=> Exited chroot $CHROOT with status $?\033[m\n"
fi