]> CyberLeo.Net >> Repos - CDN/j.git/blob - enter
enter: working revision
[CDN/j.git] / enter
1 #!/bin/sh
2 # Copyright 2011 CyberLeo, All Rights Reserved
3 # http://wiki.cyberleo.net/wiki/CyberLeo/COPYRIGHT
4
5 meh() { printf "%s\n" "${*}"; }
6 omg() { printf "%s\n" "${*}"; }
7 wtf() { printf "%s\n" "${*}"; exit 1; }
8 pebkac() {
9   [ "${*}" ] && printf "%s\n\n" "${*}"
10   cat <<EOF
11 Usage: <start|enter|stop> <jailname>
12 EOF
13   exit 1
14 }
15
16 cmd="$(basename "${0}")"
17 base="$(realpath "$(dirname "${0}")")"
18 jail="$(basename "${1:-DebianChroot}")"
19 jdir="${base}/${jail}"
20
21 [ -d "${jdir}" ] || wtf "${jail}: not a jail?"
22
23 # Propagate certain environment variables; sterilize the rest of the environment
24 env="
25   TERM=${TERM}
26   USER=${USER}
27 "
28
29 # Create a new jail (Will not work, since a new jail will not exist and will not pass the 'not a jail' check above)
30 jail_new() {
31   DEBOOTSTRAP_DIR="$(base)/debootstrap" "${DEBOOTSTRAP_DIR}/debootstrap" --arch=amd64 squeeze "${jdir}"
32 }
33
34 # Jail is 'up' if /dev/pts and /proc are mounted
35 jail_up() {
36   grep -q "^devpts ${jdir}/dev/pts devpts" /proc/mounts || return 1
37   grep -q "^proc ${jdir}/proc proc" /proc/mounts || return 1
38   return 0
39 }
40
41 # Mount /dev/pts and /proc in the jail
42 jail_start() {
43   jail_up && return 0
44   meh "starting ${jail} ..."
45   mount -t devpts devpts "${jdir}/dev/pts"
46   mount -t proc proc "${jdir}/proc"
47 }
48
49 # Enter jail
50 jail_enter() {
51   jail_up || wtf "jail not up"
52   meh "entering ${jail} ..."
53   env -i ${env} /usr/bin/chroot "${jdir}" /bin/su "${USER}" -c /bin/bash -l
54 }
55
56 # Unmount /dev/pts and /proc in the jail
57 jail_stop() {
58   jail_up || return 0
59   meh "stopping ${jail} ..."
60   umount "${jdir}/proc"
61   umount "${jdir}/dev/pts"
62 }
63
64 # Need root beyond here
65 [ "$(id -u)" -eq 0 ] || exec sudo env ${env} "${0}" "${@}"
66
67 case "${cmd}" in
68 start) jail_start ;;
69 enter) jail_enter ;;
70 stop)  jail_stop  ;;
71 *) pebkac ;;
72 esac