#!/bin/sh

url=https://s3.amazonaws.com/Minecraft.Download/versions
cd ~/servers/snapshot
wget -N --no-check-certificate $url/versions.json > /dev/null 2>&1
latest=$(grep id versions.json | head -n 1 | cut -d'"' -f4)
current=$(ls versions/*.jar -t | head -n 1 | sed -e 's/versions\/minecraft_server\.//;s/\.jar//')
if [ "$latest" != "$current" ]; then
	echo "New minecraft version ($latest) detected! Upgrading..."
	touch world.lock
	wget --no-check-certificate -nc -P versions $url/$latest/minecraft_server.$latest.jar > /dev/null 2>&1
	sed -e s/minecraft_server\.$current/minecraft_server\.$latest/g start.sh > start.sh~
	kill -USR1 `cat snapshot.tentacle`
	# wait until the server is actually shut down
	while [ 0 -lt `find world | xargs lsof | wc -l` ]; do sleep 1; done
	# do world backup
	tar -jcf backups/world-$current.tar.bz2 world
	rm world.lock
fi
