]> CyberLeo.Net >> Repos - CDN/j.git/blob - j
j: add status verb
[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 (Will not work, since a new jail will not exist and will not pass the 'not a jail' check above)
29 jail_new() {
30   DEBOOTSTRAP_DIR="$(base)/debootstrap" "${DEBOOTSTRAP_DIR}/debootstrap" --arch=amd64 squeeze "${jdir}"
31 }
32
33 # Figure out jail parameters
34 jail_params() {
35   # Where is the shell?
36   for shell in /bin/bash /usr/bin/bash /usr/local/bin/bash /bin/sh
37   do
38     if [ -f "${jdir}/${shell}" ]
39     then
40       jail_shell=${shell}
41       break
42     fi
43     wtf "cannot locate usable shell; is this a real jail?"
44   done
45 }
46
47 # Jail is 'up' if /dev/pts and /proc are mounted
48 jail_up() {
49   grep -q "^devpts ${jdir}/dev/pts devpts" /proc/mounts || return 1
50   grep -q "^proc ${jdir}/proc proc" /proc/mounts || return 1
51   return 0
52 }
53
54 jail_status() {
55   jail_up && meh "$(printf '\033[1;32mup\033[0m')" || meh "$(printf '\033[1;31mdown\033[0m')"
56 }
57
58 # Mount /dev/pts and /proc in the jail
59 jail_start() {
60   jail_up && return 0
61   meh "starting ${jail} ..."
62   mount -t devpts devpts "${jdir}/dev/pts"
63   mount -t proc proc "${jdir}/proc"
64 }
65
66 # Enter jail
67 jail_enter() {
68   jail_up || wtf "jail not up"
69   meh "entering ${jail} ..."
70   env -i ${jail_env} /usr/bin/chroot "${jdir}" /bin/su "${USER}" -c "${jail_shell}" -l
71 }
72
73 # Unmount /dev/pts and /proc in the jail
74 jail_stop() {
75   jail_up || return 0
76   meh "stopping ${jail} ..."
77   umount "${jdir}/proc"
78   umount "${jdir}/dev/pts"
79 }
80
81 # Need root beyond here
82 [ "$(id -u)" -eq 0 ] || exec sudo env ${jail_env} "${0}" "${@}"
83
84 jail_params
85
86 case "${cmd}" in
87 status) jail_status ;;
88 start) jail_start ;;
89 enter) jail_enter ;;
90 stop)  jail_stop  ;;
91 *) pebkac ;;
92 esac