summaryrefslogtreecommitdiff
path: root/runner.sh
blob: 8479159f01a277ddf934528ee60a44211c26c3b0 (plain)
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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
#!/bin/bash

# Minecraft Java runner script

function stop() {
	running || exit 0
	test -p stdin || exit 1
	echo stop > stdin

	>&2 echo -n Waiting for server to stop
	while kill -s 0 $PID > /dev/null 2>&1; do
		sleep 1
		>&2 echo -n .
	done

	>&2 echo Done!

	rm server.pid stdin

	exit 0
}

function start() {
	running && fail "Server appears to already be running. PID: $PID"

	[ -z "$JVMARGS" ] && echo 'WARNING: $JVMARGS not set'
	[ -e stdin -a ! -p stdin ] && rm stdin

	mkfifo stdin

	"$JAVA" $JVMARGS -jar "$MCJAR" -nogui $MCARGS \
		< <(while [ -p stdin ]; do timeout 10s cat stdin; done) \
		> /dev/null &
	PID=$!

	echo $PID > server.pid
	echo "Started server with PID $PID"

	exit 0
}

function attach() {
	running || fail "Server is not running."
	
	echo "CTRL-D (EOF) to exit."

	tail -f logs/latest.log &
	TAILPID=$!

	while read line; do
		echo "$line" > stdin
	done

	kill -s SIGKILL $TAILPID
	
	exit 0
}

function running() {
	[ -e server.pid ] || return 1

	PID=$(cat server.pid)
	kill -s 0 $PID && return 0

	rm server.pid stdin
	return 1
} > /dev/null 2>&1

function fail() {
	>&2 echo $@
	exit 1
}

[ -e settings.sh ] && source settings.sh \
	|| >&2 echo "WARNING: settings.sh not found."
# settings.sh
# JVMARGS, JAVA, MCARGS, MCJAR

JAVA=${JAVA:-java}
MCJAR=${MCJAR:-server.jar}

which "$JAVA" > /dev/null 2>&1 || fail "No java executable."

case $1 in
	start)
		start;;
	stop)
		stop;;
	status)
		running || fail "Server is not running."
		>&2 echo "Server is running."
		exit 0;;
	attach)
		attach;;
	command)
		running || fail "Server is not running."
		shift
		echo $@ > stdin;;
	*)
		>&2 echo "Minecraft Java server runner"
		>&2 echo "$0 start|stop|status|attach|command ..."
		fail "Invalid argument $1"
esac