74 lines
1.5 KiB
Bash
Executable File

#!/bin/bash
# constants
code_clear=$'\x05\x15'
code_send=$'\r'
die () {
echo "$@"
exit 1
}
_stop_and_wait () {
tmux $TMUX_OPTS send-keys -t "$TMUX_SESSION" -l "$code_clear" 'stop' "$code_send"
echo Waiting for session to exit...
while tmux has-session -t "$TMUX_SESSION" ; do
sleep 1
done
}
_start () {
! tmux $TMUX_OPTS has-session > /dev/null 2>&1 && \
tmux $TMUX_OPTS new-session -d -s $TMUX_SESSION "./start.sh" || \
die "Instance $instance is already running."
}
_send_command() {
tmux $TMUX_OPTS send-keys -t "$TMUX_SESSION" -l "$code_clear" "$*" "$code_send"
}
# 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, or command."
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
TMUX_OPTS="-L mcserver"
case "$cmd" in
stop) _stop_and_wait ;;
command) _send_command ;;
start|*) _start ;;
esac