]> CyberLeo.Net >> Repos - CDN/j.git/blob - enter
Init
[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 " \033[1;32m*\033[0m %s%s\n" "${jail:+${jail}: }" "${*}"; }
6 omg() { printf " \033[1;33m*\033[0m %s%s\n" "${jail:+${jail}: }" "${*}"; }
7 wtf() { printf " \033[1;31m*\033[0m %s%s\n" "${jail:+${jail}: }" "${*}"; exit 1; }
8
9 pebkac() {
10   [ "${*}" ] && printf "%s\n\n" "${*}"
11   cat <<EOF
12 Usage: <start|enter|stop> <jailname>
13 EOF
14   exit 1
15 }
16
17 cmd="$(basename "${0}")"
18 base="$(realpath "$(dirname "${0}")")"
19 jail="$(basename "${1:-DebianChroot}")"
20 jdir="${base}/${jail}"
21 jail_shell=""
22
23 # Propagate certain environment variables; sterilize the rest of the environment
24 jail_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 # Figure out jail parameters
35 jail_params() {
36   # Where is the shell?
37   for shell in /bin/bash /usr/bin/bash /usr/local/bin/bash /bin/sh
38   do
39     if [ -f "${jdir}/${shell}" ]
40     then
41       jail_shell=${shell}
42       break
43     fi
44     wtf "cannot locate usable shell; is this a real jail?"
45   done
46 }
47
48 # Jail is 'up' if /dev/pts and /proc are mounted
49 jail_up() {
50   grep -q "^devpts ${jdir}/dev/pts devpts" /proc/mounts || return 1
51   grep -q "^proc ${jdir}/proc proc" /proc/mounts || return 1
52   return 0
53 }
54
55 # Mount /dev/pts and /proc in the jail
56 jail_start() {
57   jail_up && return 0
58   meh "starting ${jail} ..."
59   mount -t devpts devpts "${jdir}/dev/pts"
60   mount -t proc proc "${jdir}/proc"
61 }
62
63 # Enter jail
64 jail_enter() {
65   jail_up || wtf "jail not up"
66   meh "entering ${jail} ..."
67   env -i ${env} /usr/bin/chroot "${jdir}" /bin/su "${USER}" -c "${jail_shell}" -l
68 }
69
70 # Unmount /dev/pts and /proc in the jail
71 jail_stop() {
72   jail_up || return 0
73   meh "stopping ${jail} ..."
74   umount "${jdir}/proc"
75   umount "${jdir}/dev/pts"
76 }
77
78 # Need root beyond here
79 [ "$(id -u)" -eq 0 ] || exec sudo env ${env} "${0}" "${@}"
80
81 jail_params
82
83 case "${cmd}" in
84 start) jail_start ;;
85 enter) jail_enter ;;
86 stop)  jail_stop  ;;
87 *) pebkac ;;
88 esac