-
Notifications
You must be signed in to change notification settings - Fork 0
/
on-cable
executable file
·89 lines (79 loc) · 2.28 KB
/
on-cable
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
#!/bin/bash
set -u -o pipefail
safe_source () { [[ ! -z ${1:-} ]] && source $1; _dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"; _sdir=$(dirname "$(readlink -f "$0")"); }; safe_source
# end of bash boilerplate
safe_source $_sdir/lib/all.sh
set +e # do not exit on error
ts(){
echo "[ `timestamp_log` ]"
}
edge=${1:-} # "attach" or "detach"
if [[ -z $edge ]]; then
echo "First parameter should be edge (attach or detach)"
exit 1
fi
hook=${2:-}
if [[ -z $hook ]]; then
echo "Hook script is required."
exit 1
fi
if [[ -f $PWD/$hook ]]; then
hook=$PWD/$hook
elif [[ -f $_sdir/$hook ]]; then
hook=$_sdir/$hook
elif `hash $hook`; then
hook=`which $hook`
else
echo "Hook script can not be found."
exit 1
fi
if [[ ! -x $hook ]]; then
echo "Hook script should be executable."
exit 1
fi
[[ $(whoami) = "root" ]] || { sudo $0 $*; exit 0; }
# re-align rest of the parameters
shift
shift
echo "Hook script will be used: $hook $*"
echo_green "`ts` Starting daemon..."
connected0=true
connected=false
check_period=2s
first_check_done=false
while true; do
if ! is_cable_plugged eth0; then
if [[ $connected0 = true ]] && [[ $connected = false ]]; then
if [[ "$edge" == "detach" ]]; then
if ! $first_check_done; then
echo_red "`ts` Cable is detached (initial status)"
first_check_done=true
else
echo_red "`ts` Cable is detached, triggering $(basename $hook)"
$hook $*
fi
else
echo_red "`ts` Cable is detached."
fi
fi
connected0=$connected
connected=false
else
if [[ $connected0 = false ]] && [[ $connected = true ]]; then
if [[ "$edge" == "attach" ]]; then
if ! $first_check_done; then
echo_green "`ts` Cable is attached (initial status)"
first_check_done=true
else
echo_green "`ts` Cable is attached, triggering $(basename $hook)"
$hook $*
fi
else
echo_green "`ts` Cable is attached."
fi
fi
connected0=$connected
connected=true
fi
sleep $check_period
done