aboutsummaryrefslogtreecommitdiff
path: root/apkg-chroot
blob: 00826f7564a4c1d257993619adc3000c906762fa (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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
#!/bin/sh
#
# script to enter chroot

printhelp() {
	cat << EOF

Usage:
  $(basename $0) <chroot-dir> [command]
  
If 'command' is unspecified, ${0##*/} will launch /bin/sh.
  
EOF
}

msgerr() {
	echo "ERROR: $*"
}

unmount() {
	while [ "$(mount | awk '{print $3}' | grep -x $1)" ]; do
		umount $1 2>/dev/null || :
	done
}

umountall() {
	for i in $(mount | awk '{print $3}' | grep $TARGET | tac); do
		unmount $i
	done
}
	
[ "$(id -u)" = "0" ] || {
	msgerr "$(basename $0) need root access!"
	printhelp
	exit 1
}

TARGET=$(realpath $1)
trap umountall 1 2 3 15

[ "$1" ] || {
	msgerr "Please set directory for chroot!"
	printhelp
	exit 1
}

[ -d "$TARGET" ] || {
	msgerr "Directory '$TARGET' not exist!"
	printhelp
	exit 1
}

shift

if [ ! "$1" ]; then
	CMD="/bin/sh"
else
	CMD=$*
fi

if [ -e /sys/firmware/efi/systab ]; then
	EFI_SYSTEM=1
fi

mount --bind /dev $TARGET/dev
mount -t devpts devpts $TARGET/dev/pts -o gid=5,mode=620
mount -t proc proc $TARGET/proc
mount -t sysfs sysfs $TARGET/sys
if [ -n "$EFI_SYSTEM" ]; then
	mount --bind /sys/firmware/efi/efivars $TARGET/sys/firmware/efi/efivars
fi
mount -t tmpfs tmpfs $TARGET/run

if [ -h $TARGET/dev/shm ]; then
  mkdir -p $TARGET/$(readlink $TARGET/dev/shm)
fi

[ -f $TARGET/etc/resolv.conf ] && {
	backupresolvconf=1
	mv $TARGET/etc/resolv.conf $TARGET/etc/resolv.conf.tmp
}
cp -L /etc/resolv.conf $TARGET/etc

chroot "$TARGET" /usr/bin/env -i \
HOME=/root \
TERM="$TERM" \
PS1='\u:\w\$ ' \
PATH=/bin:/usr/bin:/sbin:/usr/sbin $CMD

retval=$?

[ "$backupresolvconf" = 1 ] && {
	mv $TARGET/etc/resolv.conf.tmp $TARGET/etc/resolv.conf
}

unmount $TARGET/dev/pts
unmount $TARGET/dev
unmount $TARGET/run
unmount $TARGET/proc
if [ -n "$EFI_SYSTEM" ]; then
	unmount $TARGET/sys/firmware/efi/efivars
fi
unmount $TARGET/sys

exit $retval