/
stop-if-inactive.sh
executable file
·88 lines (75 loc) · 2.23 KB
/
stop-if-inactive.sh
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
#!/bin/bash
# stop-if-inactive.sh
# Schedules a shutdown if neither the c9 IDE or an ssh connection
# from specific IP addresses exists
# If either are connected, any existing shutdowns are cancelled
set -euo pipefail
CONFIG=$(cat /home/ubuntu/.c9/autoshutdown-configuration)
SHUTDOWN_TIMEOUT=${CONFIG#*=}
LOG_DIRECTORY="/tmp/.c9-log/"
LOG_FILENAME="auto-shutdown-log.txt"
LOG_FILE_PATH=$LOG_DIRECTORY$LOG_FILENAME
IP_REGEX=".*"
is_shutting_down() {
is_shutting_down_system_d &> /dev/null || is_shutting_down_init_d &> /dev/null
}
is_shutting_down_system_d() {
local TIMEOUT
TIMEOUT=$(busctl get-property org.freedesktop.login1 /org/freedesktop/login1 org.freedesktop.login1.Manager ScheduledShutdown)
if [ "$?" -ne "0" ]; then
return 1
fi
if [ "$(echo $TIMEOUT | awk "{print \$3}")" == "0" ]; then
return 1
else
return 0
fi
}
is_shutting_down_init_d() {
pgrep shutdown
}
is_vfs_connected() {
pgrep vfs-worker >/dev/null
}
is_ssh_connected() {
sudo netstat -tnpa | grep 'ESTABLISHED.*sshd' | grep "$IP_REGEX" > /dev/null
}
get_ssh_state() {
local ssh_state="disconnected"
if is_ssh_connected; then
ssh_state="connected"
fi
echo $ssh_state
}
get_vfs_state() {
local vfs_state="disconnected"
if is_vfs_connected; then
vfs_state="connected"
fi
echo $vfs_state
}
main() {
if ! [[ $SHUTDOWN_TIMEOUT =~ ^[0-9]*$ ]]; then
echo "shutdown timeout is invalid"
exit 1
fi
if is_shutting_down; then
if [[ ! $SHUTDOWN_TIMEOUT =~ ^[0-9]+$ ]] || is_vfs_connected || is_ssh_connected; then
shutdown_status="shutdown cancelled"
sudo shutdown -c
else
shutdown_status="current scheduled shutdown is still valid"
fi
elif [[ $SHUTDOWN_TIMEOUT =~ ^[0-9]+$ ]] && ! is_vfs_connected && ! is_ssh_connected; then
shutdown_status="shutdown scheduled"
sudo shutdown -h $SHUTDOWN_TIMEOUT
else
shutdown_status="N/A"
fi
mkdir -p $LOG_DIRECTORY
date > $LOG_FILE_PATH
echo "Shutdown status: "$shutdown_status >> $LOG_FILE_PATH
echo "VFS State: "$(get_vfs_state) >> $LOG_FILE_PATH
echo "SSH State: "$(get_ssh_state) >> $LOG_FILE_PATH
}
main