85 lines
1.9 KiB
Bash
Executable File

#!/bin/bash
# constants
code_clear=$'\x05\x15'
code_send=$'\r'
die () {
echo "$@"
exit 1
}
if [[ "$(id -u)" == 0 ]] ; then
die 'This script should not be run as root. Plase change the default user with `systemctl --edit mcserver@.service`'
fi
_stop_and_wait () {
tmux -L "$TMUX_SOCKET" send-keys -t "$TMUX_SESSION" -l "$code_clear" 'stop' "$code_send"
echo Waiting for session to exit...
while tmux -L "$TMUX_SOCKET" has-session -t "$TMUX_SESSION" ; do
sleep 1
done
}
_start () {
! tmux -L "$TMUX_SOCKET" has-session -t "$TMUX_SESSION" > /dev/null 2>&1 && \
tmux -L "$TMUX_SOCKET" new-session -d -s "$TMUX_SESSION" "./start.sh" || \
die "Instance $instance is already running."
}
_send_command() {
exec tmux -L "$TMUX_SOCKET" send-keys -t "$TMUX_SESSION" -l "$code_clear" "$*" "$code_send"
}
_attach() {
tmux -L "$TMUX_SOCKET" attach -t "$TMUX_SESSION"
}
# directories
mcserver_root="${XDG_DATA_HOME:-${HOME}/.local/share}/mcserver"
instances_dir="$mcserver_root/instances"
mkdir -p "$instances_dir"
cmd="$1"
shift
instance="$1"
shift
instance_dir="$instances_dir/$instance"
# input checks
if [[ -z "${cmd:+x}" ]] ; then
die "Please specify one of start, stop, command, or attach."
fi
if [[ -z "${instance:+x}" ]] ; then
die "Please specify an instance."
fi
if ! [[ -d "$instance_dir" ]] ; then
die "Instance \`$instance\` does not exist. Please create it first."
fi
cd "$instance_dir"
if ! [[ -e ./vars ]] ; then
die 'Please create a "vars" file using "vars.example" as a template.'
fi
source ./vars
# override value defined in vars for compatibility with old servers
TMUX_SESSION=mcserver-"$instance"
# set socket for tmux to separate it from user sessions
# also each server gets its own socket so systemd doesn't break
TMUX_SOCKET="mcserver-$instance"
case "$cmd" in
stop) _stop_and_wait ;;
command) _send_command "$@" ;;
start) _start ;;
attach) _attach ;;
*) die "Unknown command: $cmd";;
esac