ansible/roles/restic/files/hooks/minecraft.sh

124 lines
2.6 KiB
Bash
Raw Normal View History

2019-12-23 17:32:19 +00:00
#!/bin/bash
2019-12-27 06:04:59 +00:00
set -e
2019-12-23 17:32:19 +00:00
SERVICE=minecraft.service
VAR_DIR=/opt/minecraft/var
WAIT=30
VERBOSE=${VERBOSE:-4}
2019-12-27 06:04:59 +00:00
prereq() {
local service=$1
if ! systemctl list-units --full --all | grep -Fq "$service"; then
printf "%s unit does not exit\n" "$service"
exit 1
fi
}
2019-12-23 17:32:19 +00:00
error_exit() {
printf "%s\n" "$1" >&2
exit 1
}
stop_server() {
local unit="${1:-$SERVICE}"
local attempts="${2:-$WAIT}"
2020-01-28 06:06:49 +00:00
if ! systemctl -q is-enabled "$unit"; then
printf "%s is not enabled, skipping.\n" "$unit"
return 0
fi
2019-12-23 17:32:19 +00:00
if ! systemctl -q is-active "$unit"; then
printf "%s is already stopped\n" "$unit"
return 0
fi
2020-01-28 06:06:49 +00:00
printf "stopping %s\n" "$instance"
2019-12-23 17:32:19 +00:00
systemctl -q stop "$unit"
while systemctl -q is-active "$unit"; do
printf "waiting for %s to stop ... (%s)\n" "$unit" "$attempts"
((attempts--))
if ((attempts == 0)); then
return 1
fi
sleep 1
done
return 0
}
start_server() {
local unit="${1:-$SERVICE}"
local attempts="${2:-$WAIT}"
2020-01-26 21:18:17 +00:00
if ! systemctl -q is-enabled "$unit"; then
printf "%s is not enabled, skipping.\n" "$unit"
return 0
fi
2019-12-23 17:32:19 +00:00
if systemctl -q is-active "$unit"; then
printf "%s is already started\n" "$unit"
return 0
fi
2020-01-28 06:06:49 +00:00
printf "starting %s\n" "$instance"
2019-12-23 17:32:19 +00:00
systemctl -q start "$unit"
while ! systemctl -q is-active "$unit"; do
printf "waiting for %s to start ... (%d)\n" "$unit" "$attempts"
((attempts--))
if ((attempts == 0)); then
return 1
fi
sleep 1
done
return 0
}
open_files() {
local dir=${1-$VAR_DIR}
local attempts="${2:-$WAIT}"
while (($(lsof +D "$dir" | wc -l) > 0)); do
printf "waiting for open files ... (%d)\n" "$attempts"
((attempts--))
if ((attempts == 0)); then
return 1
fi
sleep 1
done
return 0
}
main() {
2019-12-27 06:04:59 +00:00
2019-12-23 17:32:19 +00:00
if [ "$1" == "pre" ]; then
for path in "$VAR_DIR"/*; do
instance="minecraft@$(basename "$path").service"
if ! stop_server "$instance"; then
error_exit "Failed to stop $instance"
fi
done
2019-12-23 17:32:19 +00:00
printf "checking for open files\n"
if ! open_files $VAR_DIR; then
error_exit "Open files exist in $VAR_DIR"
fi
elif [ "$1" == "post" ]; then
for path in "$VAR_DIR"/*; do
instance="minecraft@$(basename "$path").service"
if ! start_server "$instance"; then
error_exit "Failed to start $instance"
fi
done
2019-12-23 17:32:19 +00:00
fi
}
main "$@"