#! /usr/bin/env python

import sys
import os
from os.path import join, isfile, isdir, dirname, basename, abspath
from glob import glob
import shutil
import traceback
from subprocess import check_call

def enter_prompt():
    raw_input("\n\n[press enter]")

MINECRAFT_VERSION = '1.6.4'
home_dir = os.getenv('HOME')
minecraft_dir = join(home_dir, 'Library', 'Application Support', 'minecraft')
this_dir = abspath(dirname(sys.argv[0]))
try:
    mite_dir = glob(join(this_dir, MINECRAFT_VERSION + '-MITE*'))[0]
except IndexError:
    mite_dir = None
is_dedicated_server = mite_dir and mite_dir.endswith('HDS')
orig_jar = join(minecraft_dir, 'versions', MINECRAFT_VERSION, MINECRAFT_VERSION + '.jar')
mite_name = basename(mite_dir)
mite_dir_dest = join(minecraft_dir, 'versions', mite_name)
jar_name = mite_name + '.jar'
jar_path = join(mite_dir, jar_name)
resource_pack = join(mite_dir, 'MITE Resource Pack %s.zip' % MINECRAFT_VERSION)
class_dir = join(mite_dir, 'class')
staging_dir = join(this_dir, '.staging')

try:
    check_call('clear')

    if not (mite_dir and isdir(mite_dir)):
        print("Move this file (%s) into the MITE installation folder before running it." % basename(sys.argv[0]))
        enter_prompt()
        sys.exit()

    if not isfile(orig_jar):
        print("You do not have Minecraft %s installed. Please use the Minecraft launcher" % MINECRAFT_VERSION)
        print("to install version %s, then re-run this script." % MINECRAFT_VERSION)
        enter_prompt()
        sys.exit()

    # Remove, then create staging dir
    if isdir(staging_dir):
        print("Preparing")
        shutil.rmtree(staging_dir)
    os.mkdir(staging_dir)

    # Extract contents of original Minecraft jar into staging dir
    print("Extracting files")
    os.chdir(staging_dir)
    check_call(['jar', 'xf', orig_jar])

    # Remote META-INF
    shutil.rmtree('META-INF')

    # Merge the class directory with the files in the staging dir.
    print("Copying files")
    class_dir_len = len(class_dir)
    for directory, directories, files in os.walk(class_dir):
        for f in files:
            full_path = join(directory, f)
            rel_path = full_path[class_dir_len + 1:]
            new_path = join(staging_dir, rel_path)
            if not isdir(dirname(new_path)):
                os.makedirs(dirname(new_path))
            shutil.copy(full_path, new_path)

    # Create the new jar
    print("Creating %r" % basename(jar_path))
    if is_dedicated_server:
        check_call(['jar', 'cmf', join(staging_dir, 'META-INF', 'MANIFEST.MF'), jar_path] + os.listdir(staging_dir))
    else:
        check_call(['jar', 'cf', jar_path] + os.listdir(staging_dir))

    if is_dedicated_server:
        jar_path_dest = join(this_dir, jar_name)
        if isfile(jar_path_dest):
            os.remove(jar_path_dest)
        shutil.move(jar_path, jar_path_dest)
        shutil.copy(join(mite_dir, 'bash_scripts.zip'), this_dir)
        shutil.copy(join(mite_dir, 'bash_scripts.tar'), this_dir)

        print('MITE server jar has been created at this path:')
        print('\n  %s\n' % jar_path_dest)
        print('To start the server, double-click the file named "run.command" in the same folder')
    else:
        # Copy resource pack
        print('Copying %r into resource pack folder' % basename(resource_pack))
        shutil.copy(resource_pack, join(minecraft_dir, 'resourcepacks'))

        # Copy MITE dir into Minecraft versions dir
        if isdir(mite_dir_dest):
            print('Deleting previous installation of MITE')
            shutil.rmtree(mite_dir_dest)
        print('Creating Minecraft version %r' % basename(mite_dir))
        shutil.copytree(mite_dir, mite_dir_dest)

        print('MITE has been installed. Run the Minecraft launcher and edit your profile to use version %r' % basename(mite_dir))

except Exception:
    traceback.print_exc()

enter_prompt()
