aboutsummaryrefslogtreecommitdiff
path: root/bin/s
blob: 88066f3b100109fa0cfef1e3a12e7f826dc0ae02 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
#!/bin/sh

usage() {
  cat <<EOUSAGE
Usage: s [-u <user>] [-w <sec>] <COMMAND> [SERVICE...]
COMMANDS
  enable
  disable
  up
  down
  reload
  restart
EOUSAGE
  exit 1
}

fatal() {
  msg "$@" >&2
  exit 1
}

msg() {
  printf "$@\n"
}

sv_enable() {
}

sv_disable() {
}

sv_status_wants() {
  dd if="$1/supervise/status" bs=1 skip=17 count=1 2>/dev/null
}

sv_list() {
  for dir in "$1/"*; do
    status="disabled"
    color="$COLOR_FG_GREY"
    wants=""
    name="${dir##*/}"
    [ -e "${dir}/supervise/stat" ] && status=$(cat "${dir}/supervise/stat")
    [ "$status" != "disabled" ] && wants=$(sv_status_wants "${dir}")
    case "$status" in
      run)
        if [ "$wants" = "u" ]; then
          color="$COLOR_FG_GREEN"
        else
          color="$COLOR_FG_RED"
        fi
        ;;
      down)
        if [ "$wants" = "d" ]; then
          color="$COLOR_FG_GREEN"
        else
          color="$COLOR_FG_RED"
        fi
        ;;
    esac
    printf "%-20s\t$color%-10s$COLOR_FG\n" "$name" "$status"
  done
}

: ${SVCMD:=$(command -v sv)}

: ${COLOR_FG:="\e[0;37;40m"}
: ${COLOR_FG_RED="\e[0;31;40m"}
: ${COLOR_FG_GREEN="\e[0;32;40m"}
: ${COLOR_FG_GREY:="\e[1;30;40m"}

while getopts "u:w:v" opt; do
  case "$opt" in
    u) SVUSER="$OPTARG" ;;
    w) export SVWAIT="$OPTARG" ;;
  esac
done
shift $(($OPTIND - 1))

case "${SVUSER:=$USER}" in
  root)
    : ${ETCSVDIR:="/etc/sv"}
    : ${SVDIR:="/var/service"}
    ;;
  *)
    : ${ETCSVDIR:="${HOME}/sv"}
    : ${SVDIR:="${HOME}/service"}
    ;;
esac

[ -z "$1" ] && usage
case "$1" in
  ls|list) sv_list "${ETCSVDIR}" ;;
  en)
    [ -z "$2" ] && usage
    [ -d "${ETCSVDIR}/$2" ] && fatal "service '$2' does not exist"
    [ -h "$2" ] && fatal "service '$2' is already enabled"
    ln -sfv "${ETCSVDIR}/${2}" "${SVDIR}/${2}"
    ;;
  dis)
    [ -z "$2" ] && usage
    [ -d "${ETCSVDIR}/$2" ] && fatal "service '$2' does not exist"
    [ ! -h "$2" ] && fatal "service '$2' is not enabled"
    rm -v "${SVDIR}/$2"
    ;;
  x|e|X|E|D|T|c|u|d|o|t|p|h|a|i|k|q|1|2|s|r|f|restart)
    SVDIR="${SVDIR}" "${SVCMD}" "$@"
    ;;
esac