73aad9e5b0a27708fa5fe769c1266c8d0ef5c734
[packages.git] / utils / watchcat / files / watchcat.sh
1 #!/bin/sh 
2
3 mode="$1"
4
5 shutdown_now() {
6         local forcedelay="$1"
7
8         reboot &
9         
10         [ "$forcedelay" -ge 1 ] && {
11                 sleep "$forcedelay"
12
13                 echo b > /proc/sysrq-trigger # Will immediately reboot the system without syncing or unmounting your disks.
14         }
15 }
16
17 watchcat_allways() {
18         local period="$1"; local forcedelay="$2" 
19         
20         sleep "$period" && shutdown_now "$forcedelay"
21 }
22
23 watchcat_ping() {
24         local period="$1"; local forcedelay="$2"; local pinghosts="$3"; local pingperiod="$4"
25         
26         time_now="$(cat /proc/uptime)"
27         time_now="${time_now%%.*}"
28         time_last="$time_now"
29
30         while true
31         do
32                 sleep "$pingperiod"
33         
34                 time_now="$(cat /proc/uptime)"
35                 time_now="${time_now%%.*}"
36                 
37                 for host in "$pinghosts" 
38                 do
39                         if ping -c 1 "$host" &> /dev/null 
40                         then 
41                                 time_last="$time_now"
42                         else
43                                 time_diff="$((time_now-time_last))"
44                                 logger -p daemon.info -t "watchcat[$$]" "no internet connectivity for $time_diff seconds. Reseting when reaching $period"       
45                         fi
46                 done
47
48                 time_diff="$((time_now-time_last))"
49                 [ "$time_diff" -ge "$period" ] && shutdown_now "$forcedelay"
50         
51         done
52 }
53
54         if [ "$mode" = "allways" ]
55         then
56                 watchcat_allways "$2" "$3"
57         else
58                 watchcat_ping "$2" "$3" "$4" "$5"
59         fi