]> git.wh0rd.org Git - home.git/blob - .bin/custom-chroot
also mount /tmp and add a flag for adding more mounts
[home.git] / .bin / custom-chroot
1 #!/bin/bash -e
2
3 [[ -w / ]] || exec sudo env HOME="$HOME" "$0" "$@"
4
5 if [[ -z ${UNSHARE} ]] ; then
6         mount_args=
7         if type -P unshare >&/dev/null ; then
8                 UNSHARE=true exec unshare -m -- "$0" "$@"
9         fi
10 else
11         mount_args='-n'
12 fi
13 unset UNSHARE
14
15 mounts="proc sys tmp dev dev/pts usr/portage usr/portage/distfiles"
16
17 chroot=${0%/*}
18 case ${chroot} in
19         .) chroot=${PWD} ;;
20         ./*) chroot=${PWD}/${chroot#./} ;;
21 esac
22 cd "${chroot}"
23
24 do_umount() {
25         mounts=$(mount | grep ${chroot} | awk '{print $3}' | tac)
26         for m in ${mounts} ; do
27                 echo "unmounting $m"
28                 umount $m
29         done
30         if [[ -z ${mounts} ]] ; then
31                 echo "nothing mounted in ${chroot}"
32         fi
33         exit 0
34 }
35
36 while [[ -n $1 ]] ; do
37         case $1 in
38         -u) do_umount ;;
39         -m) mounts+=" $2"; shift ;;
40         -*) echo "unknown option $1"; exit 1 ;;
41         *)  break ;;
42         esac
43         shift
44 done
45
46 maybe_mount() {
47         local src=/$1 dst=${chroot}/${2:-$1}
48         [[ -d ${src} ]] || return 0
49         mkdir -p "${dst}"
50         grep -sq "${dst}" /proc/mounts || mount ${mount_args} --bind "${src}" "${dst}"
51 }
52 for m in ${mounts} ; do
53         maybe_mount ${m}
54 done
55
56 get_type() {
57         case $(file "$1") in
58                 *x86-64*)         echo x86_64;;
59                 *"Intel 80386"*)  echo i386;;
60                 *32-bit*PowerPC*) echo ppc;;
61                 *64-bit*PowerPC*) echo ppc64;;
62         esac
63 }
64 bin_dst=$(get_type bin/bash)
65 setarch=
66 if [[ -n ${bin_dst} ]] && type -P setarch &>/dev/null ; then
67         setarch="setarch ${bin_dst}"
68 fi
69
70 if [[ ! -L etc/mtab ]] ; then
71         rm -f etc/mtab
72         ln -sf /proc/mounts etc/mtab
73 fi
74 etc="
75         hosts
76         locale.gen
77         localtime
78         resolv.conf
79 "
80 home="
81         .inputrc
82         .gdbinit
83         .gitconfig
84         .nanorc
85 "
86 for f in \
87         $(printf 'etc/%s ' ${etc}) \
88 ; do
89         if [ -e "/${f}" ] ; then
90                 cp /${f} ${f}
91         fi
92 done
93 for f in ${home} ; do
94         cp ~/${f} root/${f}
95 done
96
97 unset LS_COLORS # format changes over time
98 [[ $# -eq 0 ]] && set -- env HOME=/root /bin/bash -l
99 exec \
100         ${setarch} \
101         chroot "${chroot}" \
102         "$@"