83 lines
2.0 KiB
Bash
Executable File
83 lines
2.0 KiB
Bash
Executable File
#!/bin/sh
|
|
|
|
# If exists tmux session
|
|
# If Responds to queries
|
|
|
|
SERVER_DIR='/home/ubuntu/minecraft/servers/kincls'
|
|
TMUX_NAME='minecraft kincls server'
|
|
LIVE_UNTIL="/home/ubuntu/minecraft/live_until.txt"
|
|
|
|
json_parse() {
|
|
cat - | python3 -c "import sys, json; print(json.load(sys.stdin)['$1'])"
|
|
}
|
|
|
|
silent_exitcode() {
|
|
$* > /dev/null 2>&1
|
|
}
|
|
|
|
extend_ttl() {
|
|
# Extend time to live 10 minutes at a time
|
|
new_ttl="$(date -d '+10 min' +%s)"
|
|
old_ttl="$(date -d "$(cat "$LIVE_UNTIL")" +%s)"
|
|
if [ ! -f "$LIVE_UNTIL" ] || [ "$new_ttl" -ge "$old_ttl" ]; then
|
|
# If LIVE_UNTIL file not existing or new time to live longer
|
|
echo "Extending time to live until $(date -d "@$new_ttl")"
|
|
date -d "@$new_ttl" > "$LIVE_UNTIL"
|
|
fi
|
|
exit 0
|
|
}
|
|
|
|
soft_poweroff() {
|
|
# Poweroff, if time to live has expired
|
|
ttl="0"
|
|
if [ -f "$LIVE_UNTIL" ]; then
|
|
ttl="$(date -d "$(cat "$LIVE_UNTIL")" +%s)"
|
|
fi
|
|
echo "Time to live is $(cat "$LIVE_UNTIL")"
|
|
if [ "$(date +%s)" -ge "$ttl" ]; then
|
|
echo "Server empty longer than grace time, shutting down"
|
|
empty_reset # Needs to be 0 next time server starts
|
|
tmux send-keys -t "$TMUX_NAME.0" "stop" ENTER
|
|
sleep 5
|
|
$(sudo /sbin/shutdown -P +1)
|
|
fi
|
|
exit 1
|
|
}
|
|
|
|
tmux_running() {
|
|
tmux ls -F "#{session_name}" | grep -q "$TMUX_NAME"
|
|
}
|
|
|
|
server_responsive() {
|
|
silent_exitcode mcstatus localhost ping
|
|
}
|
|
|
|
n_logins="$(w -h | wc -l)"
|
|
echo "$(date) [$n_logins logins]"
|
|
|
|
if [ "$n_logins" -gt 0 ]; then
|
|
echo "Keep alive as there are active ssh sessions"
|
|
extend_ttl
|
|
fi
|
|
|
|
if tmux_running; then
|
|
: #echo "Tmux running"
|
|
else
|
|
echo "Tmux not running"
|
|
soft_poweroff
|
|
fi
|
|
|
|
if server_responsive; then
|
|
n_players=$(mcstatus localhost json | json_parse player_count)
|
|
echo "Server responsive. $n_players players online"
|
|
if [ "$n_players" -gt 0 ]; then
|
|
# Keep alive as players are online
|
|
extend_ttl
|
|
else
|
|
soft_poweroff
|
|
fi
|
|
else
|
|
echo "Server unresponsive"
|
|
soft_poweroff
|
|
fi
|