autils

Unnamed repository; edit this file 'description' to name the repository.
git clone https://codeberg.org/emmett1/autils
Log | Files | Refs | README | LICENSE

apkg-chroot (1787B)


      1 #!/bin/sh
      2 #
      3 # script to enter chroot
      4 
      5 printhelp() {
      6 	cat << EOF
      7 
      8 Usage:
      9   $(basename $0) <chroot-dir> [command]
     10   
     11 If 'command' is unspecified, ${0##*/} will launch /bin/sh.
     12   
     13 EOF
     14 }
     15 
     16 msgerr() {
     17 	echo "ERROR: $*"
     18 }
     19 
     20 unmount() {
     21 	while [ "$(mount | awk '{print $3}' | grep -x $1)" ]; do
     22 		umount $1 2>/dev/null || :
     23 	done
     24 }
     25 
     26 umountall() {
     27 	for i in $(mount | awk '{print $3}' | grep $TARGET | tac); do
     28 		unmount $i
     29 	done
     30 }
     31 	
     32 [ "$(id -u)" = "0" ] || {
     33 	msgerr "$(basename $0) need root access!"
     34 	printhelp
     35 	exit 1
     36 }
     37 
     38 TARGET=$(realpath $1)
     39 trap umountall 1 2 3 15
     40 
     41 [ "$1" ] || {
     42 	msgerr "Please set directory for chroot!"
     43 	printhelp
     44 	exit 1
     45 }
     46 
     47 [ -d "$TARGET" ] || {
     48 	msgerr "Directory '$TARGET' not exist!"
     49 	printhelp
     50 	exit 1
     51 }
     52 
     53 shift
     54 
     55 if [ ! "$1" ]; then
     56 	CMD="/bin/sh"
     57 else
     58 	CMD=$*
     59 fi
     60 
     61 if [ -e /sys/firmware/efi/systab ]; then
     62 	EFI_SYSTEM=1
     63 fi
     64 
     65 mount --bind /dev $TARGET/dev
     66 mount -t devpts devpts $TARGET/dev/pts -o gid=5,mode=620
     67 mount -t proc proc $TARGET/proc
     68 mount -t sysfs sysfs $TARGET/sys
     69 if [ -n "$EFI_SYSTEM" ]; then
     70 	mount --bind /sys/firmware/efi/efivars $TARGET/sys/firmware/efi/efivars
     71 fi
     72 mount -t tmpfs tmpfs $TARGET/run
     73 
     74 if [ -h $TARGET/dev/shm ]; then
     75   mkdir -p $TARGET/$(readlink $TARGET/dev/shm)
     76 fi
     77 
     78 [ -f $TARGET/etc/resolv.conf ] && {
     79 	backupresolvconf=1
     80 	mv $TARGET/etc/resolv.conf $TARGET/etc/resolv.conf.tmp
     81 }
     82 cp -L /etc/resolv.conf $TARGET/etc
     83 
     84 chroot "$TARGET" /usr/bin/env -i \
     85 HOME=/root \
     86 TERM="$TERM" \
     87 PS1='\u:\w\$ ' \
     88 PATH=/bin:/usr/bin:/sbin:/usr/sbin $CMD
     89 
     90 retval=$?
     91 
     92 [ "$backupresolvconf" = 1 ] && {
     93 	mv $TARGET/etc/resolv.conf.tmp $TARGET/etc/resolv.conf
     94 }
     95 
     96 unmount $TARGET/dev/pts
     97 unmount $TARGET/dev
     98 unmount $TARGET/run
     99 unmount $TARGET/proc
    100 if [ -n "$EFI_SYSTEM" ]; then
    101 	unmount $TARGET/sys/firmware/efi/efivars
    102 fi
    103 unmount $TARGET/sys
    104 
    105 exit $retval