summaryrefslogtreecommitdiff
path: root/scripts/uchroot
blob: dd3d77a9ce1750273b3bd6cef179bb3d15aaa020 (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
54
55
#!/bin/sh
set -e
[ $# -ge 1 ] || {
	echo "Usage: uchroot USER [CMD] [ARG].." >&2
	echo "Configuration has to be passed trough envrionment."
	echo "  ROOT: path to directory to chroot in"
	echo "  ARCH: optional target architecture (if qemu should be used)"
	echo "  MOUNT: pairs of two paths separated by colon (LOCAL:INROOT)"
	exit 1
}

if [ "$(id -u)" != "0" ]; then
	exec uroot "$0" "$@"
fi
###############################################################

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

USR="${1:-root}"
shift
[ $# -lt 1 ] && CMD="" || {
	CMD="-c \"$1\""
	shift
}

[ -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
	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

exec chroot "$ROOT" /bin/sh -c \
	". /etc/profile && exec su -l $USR $CMD \"\$@\"" -- "$@"