]> git.armaanb.net Git - bin.git/blob - chrooter
signal-finder: add script
[bin.git] / chrooter
1 #!/bin/sh -e
2 # Enter a chroot nicely. Stolen from KISS Linux, MIT license Dylan Araps 2020.
3 # Some slight modifications to make life easier.
4
5 log() {
6     printf '\033[32m->\033[m %s.\n' "$*"
7 }
8
9 die() {
10     log "$*" >&2
11     exit 1
12 }
13
14 clean() {
15     log Unmounting /dev, /proc and /sys from chroot; {
16         umount "$1/sys/firmware/efi/efivars" 2>/dev/null ||:
17         umount "$1/dev"  ||:
18         umount "$1/proc" ||:
19         umount "$1/sys"  ||:
20     }
21
22     log Cleaning leftover host files; {
23         rm -f "$1/root/.ash_history"
24         rm -f "$1/etc/resolv.conf"
25     }
26 }
27
28 mounted() {
29     # This is a pure shell mountpoint implementation. We're dealing
30     # with basic (and fixed/known) input so this doesn't need to
31     # handle more complex cases.
32     [ -e "$1" ]         || return 1
33     [ -e /proc/mounts ] || return 1
34
35     while read -r _ target _; do
36         [ "$target" = "$1" ] && return 0
37     done < /proc/mounts
38
39     return 1
40 }
41
42 [ -z "$1" ]        && die Need a path to the chroot
43 [ -d "$1" ]        || die Given path does not exist
44 [ "$(id -u)" = 0 ] || die Script needs to be run as root
45
46 trap 'clean "$1"' EXIT INT
47
48 log Mounting /dev, /proc and /sys from host; {
49     mounted "$1/dev"  || mount -o bind /dev "$1/dev"  ||:
50     mounted "$1/proc" || mount -t proc proc "$1/proc" ||:
51     mounted "$1/sys"  || mount -t sysfs sys "$1/sys"  ||:
52
53     mounted "$1/sys/firmware/efi/efivars" ||
54         mount -t efivarfs efivarfs "$1/sys/firmware/efi/efivars" 2>/dev/null ||:
55 }
56
57 log Copying /etc/resolv.conf from host; {
58     cp -f /etc/resolv.conf "$1/etc" ||:
59 }
60
61 NEWSHELL=${2:-"/bin/sh"} \
62
63 log Entering chroot; {
64     chroot "$1" /usr/bin/env -i \
65         HOME=/root \
66         TERM="$TERM" \
67         SHELL=${NEWSHELL} \
68         USER=root \
69         CFLAGS="${CFLAGS:--march=x86-64 -mtune=generic -pipe -Os}" \
70         CXXFLAGS="${CXXFLAGS:--march=x86-64 -mtune=generic -pipe -Os}" \
71         MAKEFLAGS="${MAKEFLAGS:--j$(nproc 2>/dev/null || echo 1)}" \
72         DISPLAY="$DISPLAY" \
73         "$NEWSHELL" -l
74 }