summaryrefslogtreecommitdiff
path: root/scripts/uchroot
blob: 5a876c28e5501f330a876dc9cc1c650a61b2db68 (plain)
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
50
51
52
53
#!/bin/sh
# Usage: uchroot [USER [SCRIPT [ARG]..]]
# Configuration has to be passed trough envrionment.
#   ROOT: path to directory to chroot in
#   ARCH: optional target architecture (if qemu should be used)
#   MOUNT: pairs of two paths separated by colon (LOCAL:INROOT)
set -e
if [ "$(id -u)" != "0" ]; then
	exec uroot --binfmt "$0" "$@"
fi
###############################################################

[ -n "$ROOT" ] || {
	echo "Variable ROOT has to be defined in environment."
	exit 1
}

[ -d "$ROOT" ] || {
	echo "There is no such directory: $ROOT" >&2
	exit 1
}
[ -d "$ROOT/proc" -a -d "$ROOT/dev" -a -d "$ROOT/sys" ] || {
	echo "Root seems to not contain valid rootfs: $ROOT" >&2
	exit 1
}

mount --rbind "$ROOT" "$ROOT"
mount -t proc none "$ROOT/proc"
mount --rbind /dev "$ROOT/dev"
mount --rbind /sys "$ROOT/sys"
while IFS=: read src target; do
	[ -n "$src" -a -n "$target" ] || continue
	mkdir -p "$ROOT/$target"
	mount --rbind "$src" "$ROOT/$target"
done <<<"$MOUNT"

cp -f /etc/resolv.conf "$ROOT/etc/resolv.conf"
cp -f /etc/hosts "$ROOT/etc/hosts"
if [ "$ARCH" != "$(arch)" ]; then
	qemu_exec="$(which "qemu-$ARCH")"
	cp -f "$qemu_exec" "$ROOT$qemu_exec"
fi

USR="${1:-root}"
shift 2>/dev/null || true

if [ $# -gt 0 ]; then
	SCRIPT="$1"
	shift
	exec chroot "$ROOT" /bin/su -l "$USR" -- -l -c "$SCRIPT" -- "$@"
else
	exec chroot "$ROOT" /bin/su -l "$USR" -- -l
fi