improve documentation
[libremanage.git] / relay-cmd
1 #!/bin/bash
2
3 trap 'echo "$0:$LINENO:error: \"$BASH_COMMAND\" returned $?" >&2' ERR
4
5 usage() {
6 cat <<EOF
7 Usage: relay-cmd poweroff|poweron|reboot HOSTNAME|CHANNEL [RELAY_ID]
8
9 RELAY_ID is not needed if only 1 relay device is connected. To
10 understand CHANNEL and RELAY_ID, run hidusb-relay-cmd and
11 hidusb-relay-cmd state. I recommend writing a config in
12 /etc/relay-cmd.conf , then using HOSTNAME instead of CHANNEL and
13 RELAY_ID. It serves as documentation of what you connected the relay
14 to. Example config:
15
16 # This config is just sourced from bash, so make sure its valid bash.
17 # relay_id is not needed if only 1 relay is connected.
18 cephserver3_channel=1
19 cephserver3_relay_id=HURTM
20 cephserver2_channel=2
21 cephserver2_relay_id=HURTM
22 EOF
23 exit $1
24 }
25
26
27 if (( $# < 2 )); then
28 usage
29 fi
30
31 read action chan relay_id <<<"$@"
32
33 if [[ -e /etc/relay-cmd.conf ]]; then
34 source /etc/relay-cmd.conf
35 fi
36
37 # we know HOSTNAME is given if it doesn't start with a number.
38 if [[ $chan != [0-9]* ]]; then
39 chan_var=${chan}_channel
40 chan=${!chan_var}
41 if [[ ! $chan ]]; then
42 echo "error: channel not found in /etc/relay-cmd.conf" >&2
43 exit 1
44 fi
45 if [[ ! $relay_id ]]; then
46 relay_id_var=${chan}_relay_id
47 relay=${!relay_id_var}
48 fi
49 fi
50
51
52 if hidusb-relay-cmd state | grep ON; then
53 printf "%s\n" "WARNING: output from hidusb-relay-cmd state shows an ON relay. this could mean another command instance is running, or it got stuck on due to an uncompleted command." >&2
54 fi
55
56
57 case $(hidusb-relay-cmd state|wc -l) in
58 0)
59 echo "error: got 0 lines from running hidusb-relay-cmd state" >&2
60 exit 1
61 ;;
62 1) : ;;
63 *)
64 if [[ ! $relay_id ]]; then
65 echo "error: more than 1 relay device, so passing its id is required" >&2
66 exit 1
67 fi
68 ;;
69 esac
70
71
72 if [[ $relay_id ]]; then
73 # leave this as an empty var if its not passed
74 relay_id_arg="id=$relay_id"
75 fi
76
77 # verbose command
78 v() {
79 printf "+ %s\n" "$*"
80 "$@"
81 }
82
83
84 # ignore hup so we complete even if there is a connection problem.
85 trap '' HUP
86 echo "$0: doing $action. shell commands are printed to the terminal:"
87 case $action in
88 poweroff)
89 v hidusb-relay-cmd $relay_id_arg on $chan
90 v sleep 6
91 v hidusb-relay-cmd $relay_id_arg off $chan
92 ;;
93 poweron)
94 v hidusb-relay-cmd $relay_id_arg on $chan
95 v sleep 1
96 v hidusb-relay-cmd $relay_id_arg off $chan
97 ;;
98 reboot)
99 v hidusb-relay-cmd $relay_id_arg on $chan
100 v sleep 6
101 v hidusb-relay-cmd $relay_id_arg off $chan
102 v sleep 1
103 v hidusb-relay-cmd $relay_id_arg on $chan
104 v sleep 1
105 v hidusb-relay-cmd $relay_id_arg off $chan
106 ;;
107 *)
108 echo "error: action arg not supported" >&2
109 exit 1
110 esac
111 echo "$0: script ended. exiting"