from os import remove, symlink

from requests import get


manifest = get('https://launchermeta.mojang.com/mc/game/version_manifest.json')
versions = manifest.json()['versions']
for version in versions:
    if version['type'] == 'release':
        break

server_id = version['id']
print(f'Found version {server_id}')

latest_info_url = version['url']
latest_info = get(latest_info_url)
server_url = latest_info.json()['downloads']['server']['url']

server = get(server_url)

fname = f'minecraft_server.{server_id}.jar'
fullpath = f'/home/ubuntu/minecraft/{fname}'
print(f'Writing to {fullpath}')
with open(fname, 'wb') as f:
    f.write(server.content)

linkname = '/home/ubuntu/minecraft/server.jar'
print(f'Symlinking {linkname} to {fullpath}')
try:
    remove(linkname)
except FileNotFoundError:
    pass
symlink(fname, linkname)
