-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathchroot.sh
executable file
·104 lines (86 loc) · 2.33 KB
/
chroot.sh
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
#!/bin/bash -e
readonly FILE_SCRIPT="$(basename "$0")"
readonly DIR_SCRIPT="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null 2>&1 && pwd )"
help() {
echo
echo "Usage: ${FILE_SCRIPT} <options>"
echo
echo " required:"
echo " -r --rootfs_base Debian ROOTFS_BASE Directory (May also be exported to environment)"
echo
echo "Example:"
echo "${FILE_SCRIPT} -r ~/git/varigit/bsps/debian-bullseye/debian_imx8qm-var-som/rootfs"
echo
exit
}
parse_args() {
while [[ $# -gt 0 ]]; do
case $1 in
-h|--help)
help
;;
-r|--rootfs_base)
ROOTFS_BASE="$2"
shift # past argument
shift # past value
;;
-c|--command)
COMMAND="$2"
shift # past argument
shift # past value
;;
*) # unknown option
echo "Unknown option: $1"
help
;;
esac
done
}
parse_args "$@"
if [ -z "${ROOTFS_BASE}" ]; then
help
fi
if [ ! -d "${ROOTFS_BASE}" ]; then
echo "Error, rootfs directory not found ${ROOTFS_BASE}"
help
fi
# Mount Points
mount_dirs=("/proc" "/dev" "/dev/pts" "/sys" )
chroot_prepare() {
sudo cp /usr/bin/qemu-aarch64-static ${ROOTFS_BASE}/usr/bin/qemu-aarch64-static
# Loop through array, mounting directories
for i in ${!mount_dirs[@]}; do
mount_dir=${mount_dirs[$i]}
MOUNT_CMD="sudo mount -o bind ${mount_dir} ${ROOTFS_BASE}${mount_dir}"
echo "${MOUNT_CMD}"
${MOUNT_CMD}
done
sudo mkdir -p ${ROOTFS_BASE}/workdir
sudo mount -o bind ${DIR_SCRIPT} ${ROOTFS_BASE}/workdir
}
chroot_cleanup() {
# Loop through array, unmounting directories
for ((i=${#mount_dirs[@]}-1; i>=0; i--)); do
mount_dir=${mount_dirs[$i]}
MOUNT_CMD="sudo umount ${ROOTFS_BASE}${mount_dir}"
echo "${MOUNT_CMD}"
${MOUNT_CMD}
done
sudo umount ${ROOTFS_BASE}/workdir
}
# Set up the trap command to run the cleanup function
trap 'chroot_cleanup EXIT' EXIT
# Make sure not already mounted
if [ -n "$(mount | grep -i "${ROOTFS_BASE}")" ]; then
echo "Error, ${ROOTFS_BASE} is already mounted"
set +e
chroot_cleanup
exit -1
fi
chroot_prepare
if [ -n "${COMMAND}" ]; then
sudo chroot ${ROOTFS_BASE}/ /bin/bash -c "${COMMAND}"
else
sudo chroot ${ROOTFS_BASE}/
fi
sleep 0.5