mtsc/matter-chroot/main.sh

119 lines
3.0 KiB
Bash
Executable File

#!/bin/bash
# matter-chroot | MatterLinux chroot script
# MatterLinux 2023-2024 (https://matterlinux.xyz)
# 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/>.
#############################
## import common functions ##
#############################
location="$(dirname "${0}")"
location="$(realpath "${location}")"
commonsh="$(echo "${location}" | sed 's/\/bin/\/lib/g')/mtsc-common.sh"
source "${commonsh}"
if [ "${?}" != "0" ]; then
echo "Failed to import mtsc-common"
exit 1
fi
####################
## util functions ##
####################
linkresolv(){
if [ ! -f "${target}/etc/resolv.conf" ]; then
ln -sf /run/systemd/resolve/resolv.conf "${target}/etc/resolv.conf"
fi
}
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
if [ -h "${target}/dev/shm" ]; then
mkdir -p "${target}/$(readlink "${target}/dev/shm")"
else
mount -t tmpfs -o nosuid,nodev tmpfs "${target}/dev/shm"
fi
local prompt='\['$BOLD'\['$RED'(chroot)\['$RESET'\['$BOLD' \u@\h:\w#\['$RESET' '
chroot "${target}" /usr/bin/env -i \
HOME=/root \
TERM="${TERM}" \
PS1="${prompt}" \
PATH=/usr/bin:/usr/sbin \
"$@"
local ret_code=$?
# kill procs that may prevent umount
killall -9 keyboxd 2> /dev/null
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"
return $ret_code
}
#################
## main script ##
#################
if [ "$EUID" -ne 0 ]; then
error "Cannot chroot without root"
exit 1
fi
if [ $# -eq 0 ]; then
error "Please specify a directory"
exit 1
fi
target="$(realpath "${1}")"
if [ -f "${target}" ]; then
error "${target} is a file"
exit 1
fi
if [ ! -d "${target}" ]; then
error "${target} does not exist"
exit 1
fi
if [ $# -gt 1 ]; then
chrt ${@:2}
exit $?
fi
chrt bash --noprofile --login
exit $?