]> CyberLeo.Net >> Repos - CDN/j.git/blob - j
j: rename jail_new to jail_init; recomment
[CDN/j.git] / j
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 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="${J_BASE:-$(realpath "$(dirname "${0}")/../")}"
18 jail="${J_NAME:-$(basename "${1:-DebianChroot}")}" #"
19 jdir="${base}/${jail}"
20 jail_shell=""
21
22 # Propagate certain environment variables; sterilize the rest of the environment
23 jail_env="
24   TERM=${TERM}
25   USER=${USER}
26 "
27
28 # Create a new jail, somehow
29 jail_init() {
30   # Either a debian jail with debootstrap or a gentoo jail with stage3 + portage tarballs
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 jail_status() {
56   jail_up && meh "$(printf '\033[1;32mup\033[0m')" || meh "$(printf '\033[1;31mdown\033[0m')"
57 }
58
59 # Mount /dev/pts and /proc in the jail
60 jail_start() {
61   jail_up && return 0
62   meh "starting ${jail} ..."
63   mount -t devpts devpts "${jdir}/dev/pts"
64   mount -t proc proc "${jdir}/proc"
65 }
66
67 # Enter jail
68 jail_enter() {
69   jail_up || wtf "jail not up"
70   meh "entering ${jail} ..."
71   env -i ${jail_env} /usr/bin/chroot "${jdir}" /bin/su "${USER}" -c "${jail_shell}" -l
72 }
73
74 # Unmount /dev/pts and /proc in the jail
75 jail_stop() {
76   jail_up || return 0
77   meh "stopping ${jail} ..."
78   umount "${jdir}/proc"
79   umount "${jdir}/dev/pts"
80 }
81
82 # Need root beyond here
83 [ "$(id -u)" -eq 0 ] || exec sudo env ${jail_env} "${0}" "${@}"
84
85 jail_params
86
87 case "${cmd}" in
88 status) jail_status ;;
89 start) jail_start ;;
90 enter) jail_enter ;;
91 stop)  jail_stop  ;;
92 *) pebkac ;;
93 esac