mtsc/matter-chroot/main.sh

109 lines
2.7 KiB
Bash
Raw Normal View History

2023-12-22 17:44:46 +00:00
#!/bin/bash
# matter-chroot | Matterlinux Chroot Script
# Copyright (C) 2023 Matterlinux
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
############################
## logging functions/vars ##
############################
RED="\e[31m"
BOLD="\e[1m"
RESET="\e[0m"
error() {
echo -e "$BOLD$RED>>>$RESET$BOLD $1$RESET"
exit 1
}
####################
## util functions ##
####################
linkresolv(){
if [ ! -f "$TARGET/etc/resolv.conf" ]; then
ln -sf /run/systemd/resolve/resolv.conf "$TARGET/etc/resolv.conf"
fi
}
2023-12-22 17:44:46 +00:00
chrt() {
mount -t proc proc "$TARGET/proc"
mount -t sysfs sysfs "$TARGET/sys"
if [[ -d "$TARGET/sys/firmware/efi/efivars" ]]; then
mount -t efivarfs efivarfs "$TARGET/sys/firmware/efi/efivars"
fi
mount -o bind /dev "$TARGET/dev"
mount -t devpts none "$TARGET/dev/pts"
mount --bind /run "$TARGET/run"
linkresolv
2023-12-22 17:44:46 +00:00
if [ -h $TARGET/dev/shm ]; then
mkdir -p $TARGET/$(readlink $TARGET/dev/shm)
else
mount -t tmpfs -o nosuid,nodev tmpfs "$TARGET/dev/shm"
2023-12-22 17:44:46 +00:00
fi
2024-01-07 11:19:11 +00:00
local prompt='\['$BOLD'\['$RED'(chroot)\['$RESET'\['$BOLD' \u@\h:\w#\['$RESET' '
chroot "$TARGET" /usr/bin/env -i \
2023-12-22 17:44:46 +00:00
HOME=/root \
TERM="$TERM" \
PS1="$prompt" \
PATH=/usr/bin:/usr/sbin \
"$@"
RET_CODE=$?
# kill procs that may prevent umount
killall -9 dirmngr 2> /dev/null
killall -9 gpg-agent 2> /dev/null
umount "$TARGET/proc"
mountpoint -q "$TARGET/sys/firmware/efi/efivars" && umount "$TARGET/sys/firmware/efi/efivars"
umount "$TARGET/sys"
umount "$TARGET/dev/pts"
mountpoint -q "$TARGET/dev/shm" && umount "$TARGET/dev/shm"
umount "$TARGET/dev"
umount "$TARGET/run"
2023-12-22 17:44:46 +00:00
}
#################
## main script ##
#################
if [ "$EUID" -ne 0 ]; then
error "Cannot chroot without root"
fi
2023-12-22 17:44:46 +00:00
if [ $# -eq 0 ]; then
error "Please specify a directory"
fi
TARGET=$(realpath $1)
if [ -f $TARGET ]; then
error "$TARGET is a file"
fi
if [ ! -d $TARGET ]; then
error "$TARGET does not exist"
fi
if [ $# -gt 1 ]; then
chrt ${@:2}
exit $RET_CODE
2023-12-22 17:44:46 +00:00
fi
2024-01-18 15:02:56 +00:00
chrt bash --noprofile --login
exit $?