#!/usr/bin/env python
from __future__ import print_function
import json
import os
import sys

# User Variables
TYPE = "release" # "release" or "snapshot"
JAR_NAME = "{version}.jar"
LINK_NAME = "server.jar"

# The manifest URL, this should not change. Follow @dinnerbone for updates
MANIFEST_URL = "https://launchermeta.mojang.com/mc/game/version_manifest.json"

# Version specific stuff
if sys.version_info[0] >= 3:
    import urllib.request
    def getPage(url):
        with urllib.request.urlopen(url) as response:
            return response.read()
else:
    import urllib2
    def getPage(url):
        req = urllib2.Request(url)
        response = urllib2.urlopen(req)
        return response.read()

# Actual script starts here

# First figure out what the latest version is
manifest_data = json.loads(getPage(MANIFEST_URL))
version = manifest_data["latest"][TYPE]
filename = JAR_NAME.format(version=version)

if os.path.exists(filename):
    print("error: {filename} already exists!".format(filename=filename))
    sys.exit(1)

# Figure out the url for the version we want
version_data = [d for d in manifest_data["versions"] if d["id"] == version][0]
version_manifest = json.loads(getPage(version_data["url"]))
download_url = version_manifest["downloads"]["server"]["url"]

with open(filename, "w") as serverjar:
    serverjar.write(getPage(download_url))

if os.path.exists(LINK_NAME):
    os.remove(LINK_NAME)

os.symlink(filename, LINK_NAME)