summaryrefslogtreecommitdiff
path: root/servicectl
blob: df965065e4461e550afd6daecbdad51a17c12a0e (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
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
#!/usr/bin/env bash

## CHECK DEPS

if ! type readlink >/dev/null 2>&1; then
  printf "readlink command not found.\n"
  exit 1
fi

## UTIL FUNCTIONS

reverse_array () {
  unset _b
  for a in $@; do
    [ -n "$_b" ] && _b="$a $_b" || _b="$a"
  done
  echo $_b
}

## FIND INIT

INIT="$(readlink $(type init) )"
if `type s6-rc >/dev/null`; then
  S6=y
else
  unset S6
fi

if [ "$INIT" = "openrc-init" ]; then
  OPENRC=y
  unset RUNIT DINIT
fi

## CHECK PRIVS

if [ "$(whoami)" != "root" ]; then
  ROOTCMD="sudo"
fi

## SERVICE FUNCTIONS

start_service () {
  if [ -n "$S6" ]; then
    $ROOTCMD s6-rc -u change $1
  fi
  if [ -n "$OPENRC" ]; then
    $ROOTCMD rc-service $1 start
  fi
}

stop_service () {
  if [ -n "$S6" ]; then
    $ROOTCMD s6-rc -d change $1
  fi
  if [ -n "$OPENRC" ]; then
    $ROOTCMD rc-service $1 stop
  fi
}

enable_service () {
  if [ -n "$S6" ]; then
    $ROOTCMD s6-service add default $1
  fi
  if [ -n "$OPENRC" ]; then
    $ROOTCMD rc-update add $1 default
  fi
}

disable_service () {
  if [ -n "$S6" ]; then
    $ROOTCMD s6-service delete default $1
  fi
  if [ -n "$OPENRC" ]; then
    $ROOTCMD rc-update del $1 default
  fi
}

status_service () {
  if [ -n "$S6" ]; then
    $ROOTCMD s6-rc -a list
  fi
  if [ -n "$OPENRC" ]; then
    $ROOTCMD rc-service status
  fi
}

## MAIN LOOP

case "$1" in
  "start")
    for i in "${@:2}"; do
      printf "start $i\n"
      start_service $i
    done
    ;;
  "stop")
    for i in "${@:2}"; do
      printf "stop $i\n"
      stop_service $i
    done
    ;;
  "enable")
    for i in "${@:2}"; do
      printf "enable $i\n"
      enable_service $i
    done
    ;;
  "disable")
    for i in "${@:2}"; do
      printf "disable $i\n"
      disable_service $i
    done
    ;;
  "restart")
    for i in `reverse_array ${@:2}`; do
      printf "stop $i\n"
      stop_service $i
    done
    for i in ${@:2}; do
      printf "start $i\n"
      start_service $i
    done
    ;;
  "status")
    status_service
esac