future-install-scripts/arch-chroot.in
2023-03-03 19:27:04 +08:00

88 lines
2.1 KiB
Bash

#!/bin/bash
shopt -s extglob
# m4_include() is recognized as a function definition
# shellcheck source=common disable=SC1073,SC1065,SC1064,SC1072
m4_include(common)
setup=chroot_setup
unshare=0
userspec=''
chroot_args=()
usage() {
cat <<EOF
usage: ${0##*/} [options] chroot_dir [command [arguments...]]
Options:
-N Run in unshare mode as a regular user
-u <user>[:group] Specify non-root user and group (optional) to use
-h Print this help message
If 'command' is unspecified, arch-chroot will launch /bin/bash.
Note that when using arch-chroot, the target chroot directory *should* be a
mountpoint. This ensures that tools such as pacman(8) or findmnt(8) have an
accurate hierarchy of the mounted filesystems within the chroot.
If your chroot target is not a mountpoint, you can bind mount the directory on
itself to make it one, i.e. 'mount --bind chroot_dir chroot_dir'.
EOF
}
if [[ -z $1 || $1 = @(-h|--help) ]]; then
usage
exit $(( $# ? 0 : 1 ))
fi
while getopts ':Nu:' flag; do
case $flag in
N)
setup=unshare_setup
unshare=1
;;
u)
userspec="$OPTARG"
;;
:)
die "%s: option requires an argument -- '%s'" "${0##*/}" "$OPTARG"
;;
?)
die "%s: invalid option -- '%s'" "${0##*/}" "$OPTARG"
;;
esac
done
shift $(( OPTIND - 1 ))
(( $# )) || die 'No chroot directory specified'
chrootdir="$1"; shift
if ! mountpoint -q "$chrootdir"; then
warning '%s is not a mountpoint, and thus may cause undesirable side effects. (See help for more info)' "$chrootdir"
fi
command=("$@")
arch-chroot() {
check_root
[[ -d "$chrootdir" ]] || die '%s: not a directory' "$chrootdir"
$setup "$chrootdir"
chroot_add_resolv_conf "$chrootdir" || die 'Failed to setup resolv.conf in chroot'
[[ $userspec ]] && chroot_args+=(--userspec="$userspec")
SHELL=/bin/bash $pid_unshare chroot "${chroot_args[@]}" -- "$chrootdir" "${command[@]}"
}
if (( unshare )); then
$mount_unshare bash -c "$(declare_all); arch-chroot"
else
arch-chroot
fi
# vim: et ts=2 sw=2 ft=sh: