]> git.wh0rd.org - home.git/blob - .bin/custom-chroot
use unshare if available
[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 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 -*) echo "unknown option $1"; exit 1 ;;
40 *) break ;;
41 esac
42 done
43
44 maybe_mount() {
45 local src=/$1 dst=${chroot}/${2:-$1}
46 [[ -d ${src} ]] || return 0
47 mkdir -p "${dst}"
48 grep -sq "${dst}" /proc/mounts || mount ${mount_args} --bind "${src}" "${dst}"
49 }
50 for m in ${mounts} ; do
51 maybe_mount ${m}
52 done
53
54 get_type() {
55 case $(file "$1") in
56 *x86-64*) echo x86_64;;
57 *"Intel 80386"*) echo i386;;
58 *32-bit*PowerPC*) echo ppc;;
59 *64-bit*PowerPC*) echo ppc64;;
60 esac
61 }
62 bin_dst=$(get_type bin/bash)
63 setarch=
64 if [[ -n ${bin_dst} ]] && type -P setarch &>/dev/null ; then
65 setarch="setarch ${bin_dst}"
66 fi
67
68 if [[ ! -L etc/mtab ]] ; then
69 rm -f etc/mtab
70 ln -sf /proc/mounts etc/mtab
71 fi
72 etc="
73 hosts
74 locale.gen
75 localtime
76 resolv.conf
77 "
78 home="
79 .inputrc
80 .gdbinit
81 .gitconfig
82 .nanorc
83 "
84 for f in \
85 $(printf 'etc/%s ' ${etc}) \
86 ; do
87 if [ -e "/${f}" ] ; then
88 cp /${f} ${f}
89 fi
90 done
91 for f in ${home} ; do
92 cp ~/${f} root/${f}
93 done
94
95 unset LS_COLORS # format changes over time
96 [[ $# -eq 0 ]] && set -- env HOME=/root /bin/bash -l
97 exec \
98 ${setarch} \
99 chroot "${chroot}" \
100 "$@"