dchr/run.sh

84 lines
1.7 KiB
Bash
Raw Permalink Normal View History

2024-04-09 09:41:04 +03:00
#!/usr/bin/env bash
help () {
2024-04-10 08:32:08 +03:00
echo 'dchr-run [options] <chroot-dir> [command]'
echo '-- options:'
echo ' -u uid[:gid] invoke command in chroot as a different user'
# TODO:
#echo ' -x11 apply options for correctly starting GUI apps'
2024-04-09 09:41:04 +03:00
echo 'https://dchr.dc09.ru'
}
clean () {
echo '-- Cleaning up'
umount "$1/proc"
umount "$1/sys"
umount "$1/dev"
umount "$1/run"
}
error () {
echo -e '-- \e[1;31mError\e[0m -- see output above'
exit 1 # `trap` in main() calls cleanup function
}
setup () {
echo '-- Mounting'
mount -t proc /proc "$1/proc" || error
mount -t sysfs /sys "$1/sys" || error
mount -o bind /dev "$1/dev" || error
mount -o bind /run "$1/run"
}
runcmd () {
echo -e '-- \e[1;32mOK\e[0m -- running chroot'
userspec="$1"
2024-04-10 08:32:08 +03:00
chrdir="$2"
shift 2
2024-04-09 16:49:52 +03:00
chrcmd=("$@")
[[ "$userspec" != "" ]] && \
chroot "--userspec=$userspec" "$chrdir" "${chrcmd[@]}" || \
chroot "$chrdir" "${chrcmd[@]}"
2024-04-09 09:41:04 +03:00
}
main () {
2024-04-09 10:29:50 +03:00
[[ "$1" == "--help" || "$1" == "" ]] && help && exit 0
2024-04-09 09:41:04 +03:00
userspec=""
2024-04-10 08:32:08 +03:00
while [[ "$1" == -* ]]
do
case "$1" in
-u)
userspec="$2"
shift 2
;;
#-x11);; TODO
*)
echo -ne '-- \e[1mInvalid option:\e[0m '
echo "$1"
echo '-- Use ./ or full path if your chroot-dir starts with dash (-)'
help
exit 2
;;
esac
done
chrdir=$(readlink -f "$1")
2024-04-09 16:49:52 +03:00
shift
2024-04-09 09:41:04 +03:00
trap "clean \"$chrdir\"" EXIT
2024-04-09 09:41:04 +03:00
setup "$chrdir"
2024-04-10 08:32:08 +03:00
runcmd "$userspec" "$chrdir" "$@"
2024-04-09 09:41:04 +03:00
exit $?
}
sourced () {
2024-04-09 09:47:13 +03:00
[ -n "$ZSH_VERSION" ] && [[ "$ZSH_EVAL_CONTEXT" =~ :file ]] && return 0
2024-04-09 10:29:50 +03:00
[ -n "$BASH_VERSION" ] && [[ "$0" != "$BASH_SOURCE" ]] && return 0
2024-04-09 09:41:04 +03:00
return 1
}
sourced || main "$@"