#!/usr/bin/env python

import sys
import argparse
import os.path
import os

from lib import const
from lib.core import ssh_exec, ssh_exec_all, ssh_get, scp_r, scp_r_remote_to_local
from lib.playground_config import PlaygroundConfig, load_playground_config

this_dir = os.path.dirname(os.path.realpath(__file__))
oogway_relative_dir = os.path.join(this_dir, "../oogway")
sys.path.append(oogway_relative_dir)

from lib.playground.ipython import *
from lib.playground.nginx import *
from lib.playground.process_management import *
from lib.playground.rsyslog import *
from lib.playground.spigot_grpc import *
from lib.playground.sponge_mcpi import *
from lib.playground.staging_files import *
from lib.playground.teleport import *
from lib.playground.util import *
from lib.playground.windows_client import *

parser = argparse.ArgumentParser()
parser.add_argument('playground_name', type=str, help='help TODO')
subparsers = parser.add_subparsers(help='sub-command help')

def add_simple_subparser(f):
    command_name = f.__name__.replace("_", "-")
    p = subparsers.add_parser(command_name, help='{} help'.format(command_name))
    p.set_defaults(func=f)

def exists(args):
    ssh_exec("file {}".format(pdir(args.playground_name)))
add_simple_subparser(exists)

def status(args):
    # TODO: should be better
    ssh_exec("file {} || true".format(pdir(args.playground_name)))
add_simple_subparser(status)

def test_overlay(args):
    playground_config = load_playground_config(args.playground_name, args.playground_config_file)
    stage_overlay_files(playground_config)
    stage_generated_files(playground_config)
    create_and_link_shared2_dir(playground_config)
    create_and_link_all_notebook_dir(playground_config)
test_overlay_parser = subparsers.add_parser("test-overlay", help='{} overlay')
test_overlay_parser.add_argument('playground_config_file', help='json config for playgrounds')
test_overlay_parser.set_defaults(func=test_overlay)

def overlay(args):
    playground_config = load_playground_config(args.playground_name, args.playground_config_file)
    stage_overlay_files(playground_config)
    stage_generated_files(playground_config)
    create_and_link_shared2_dir(playground_config)
    create_and_link_share_file(playground_config)
    create_and_link_all_notebook_dir(playground_config)
    clean_remote_dirs(args.playground_name)
    upload_staged_files(args.playground_name)
    reset_basic_auth_password(args.playground_name, playground_config.web_password)
    prepare_client_log(args.playground_name)
    prepare_console_log(args.playground_name)
    set_directory_execute(args.playground_name) # something was stripping execute...um not sure what.
    reload_nginx()
    write_crontab(args)
    write_rsyslog_conf(args)
    write_ipython_notebook_html()
overlay_parser = subparsers.add_parser("overlay", help='{} overlay')
overlay_parser.add_argument('playground_config_file', help='json config for playgrounds')
overlay_parser.set_defaults(func=overlay)

def create(args):
    playground_config = load_playground_config(args.playground_name, args.playground_config_file)
    ssh_exec("mkdir -p {}".format(pdir(args.playground_name)))
    copy_minecraft_server_files(args.playground_name)
    copy_spigot_server_files(playground_config)
    refresh_ipython(args)
    overlay(args)
    write_crontab(args)
create_parser = subparsers.add_parser("create", help='{} overlay')
create_parser.add_argument('playground_config_file', help='json config for playgrounds')
create_parser.set_defaults(func=create)

def kill_if_listening_on_port(port_number):
    ssh_exec("fuser -vk {}/tcp || true".format(port_number))

def stop_ipython(args):
    tmux_kill(args.playground_name + "-py")
add_simple_subparser(stop_ipython)

def stop_minecraft(args):
    tmux_kill(args.playground_name + "-mc")
add_simple_subparser(stop_minecraft)

def start_ipython(args):
    tmux_start(args.playground_name, "-py", "tmux_restart_ipython_notebook_server")
add_simple_subparser(start_ipython)

def start_minecraft(args):
    tmux_start(args.playground_name, "-mc", "tmux_restart_minecraft_server")
add_simple_subparser(start_minecraft)

def minecraft_tunnel_jvm(args):
    playground_config = load_playground_config(args.playground_name, args.playground_config_file)
    exec_minecraft_tunnel_jvm(playground_config)
exec_minecraft_tunnel_jvm_parser = subparsers.add_parser("minecraft-tunnel-jvm", help='{} minecraft-tunnel-jvm')
exec_minecraft_tunnel_jvm_parser.add_argument('playground_config_file', help='json config for playgrounds')
exec_minecraft_tunnel_jvm_parser.set_defaults(func=minecraft_tunnel_jvm)

def refresh_ipython(args):
    ssh_exec_all([
        "mkdir -p {}".format(ipython_data_dir(args.playground_name)),
        "rm -rf {}/ipython-notebook-root/lib".format(pdir(args.playground_name)),
        "mkdir -p {}/ipython-notebook-root/lib".format(pdir(args.playground_name)),
        "cp -r mcpi/mcpi {}/ipython-notebook-root/lib/".format(pdir(args.playground_name)),
        "cp -r mcgamedata/mcgamedata {}/ipython-notebook-root/lib/".format(pdir(args.playground_name)),
        "cp -r oogway/oogway {}/ipython-notebook-root/lib/".format(pdir(args.playground_name)),
        "mkdir -p {}/ipython-notebook-root/lib/codeshare".format(pdir(args.playground_name))
    ])
    scp_r(this_dir + "/codeshare/extract.py", "{}/ipython-notebook-root/lib/codeshare/".format(pdir(args.playground_name)))
    scp_r(this_dir + "/codeshare/ipynb_util.py", "{}/ipython-notebook-root/lib/codeshare/".format(pdir(args.playground_name)))
    scp_r(this_dir + "/codeshare/document.py", "{}/ipython-notebook-root/lib/codeshare/".format(pdir(args.playground_name)))
add_simple_subparser(refresh_ipython)

def copy_ipynb(args):
    playground_config = load_playground_config(args.playground_name, args.playground_config_file)
    source_playground_config = load_playground_config(args.source_playground_name, args.playground_config_file)
    quick_backup_ipython_notebooks(args.playground_name)
    existing_ipynb_wildcard = os.path.join(ipython_data_dir(args.playground_name), args.ipynb_wildcard + ".ipynb")
    ipynb_wildcard = os.path.join(ipython_data_dir(args.source_playground_name), args.ipynb_wildcard + ".ipynb")
    ipynbs = ssh_get("ls {}".format(ipynb_wildcard)).strip().split("\n")

    if len(ipynbs) == 0:
        raise Exception("No ipython notebooks found matching {}".format(ipynb_wildcard))
    else:
        print("will copy:")
        for ipynb in ipynbs:
            print(ipynb)
    ssh_exec("rm {} || true".format(existing_ipynb_wildcard))
    ssh_exec("cp {} {}/{}".format(ipynb_wildcard, ipython_data_dir(args.playground_name), args.dest_subdir))

    for ipynb in ipynbs:
        ipynb_relative_path = ipynb.replace(ipython_data_dir(args.source_playground_name) + "/", "")
        ipynb_relative_path = args.dest_subdir + "/" + ipynb_relative_path
        create_client_url_switch_scripts(source_playground_config, playground_config, ipynb_relative_path)

    ssh_exec("mkdir -p {}".format(pdir(args.playground_name) + "/bin/url"))
    scp_r(DEST_URL_BIN_PREP_DIR + "/.", pdir(args.playground_name) + "/bin/url")
    ssh_exec("mkdir -p {}".format(pdir(args.source_playground_name) + "/bin/url"))
    scp_r(SOURCE_URL_BIN_PREP_DIR + "/.", pdir(args.source_playground_name) + "/bin/url")

    stage_overlay_files(source_playground_config)
    create_nginx_location_directives_for_bin_files(
        source_playground_config,
        get_bin_files_on_server_and_staged(source_playground_config),
        OVERLAY_STAGING_DIR + "/nginx.conf",
        OVERLAY_STAGING_DIR + "/webroot/index.html")
    scp_r(OVERLAY_STAGING_DIR + "/nginx.conf", "{}/nginx.conf".format(pdir(args.source_playground_name)))
    scp_r(OVERLAY_STAGING_DIR + "/webroot/index.html", "{}/webroot/index.html".format(pdir(args.source_playground_name)))
    reload_nginx()

copy_ipynb_parser = subparsers.add_parser("copy-ipynb", help='{} copy-ipynb')
copy_ipynb_parser.add_argument('source_playground_name', help='the playground that has the ipython notebook(s)')
copy_ipynb_parser.add_argument('ipynb_wildcard', help='wildcard that matches ipython notebook(s)')
copy_ipynb_parser.add_argument('dest_subdir', help='destination subdirectory')
copy_ipynb_parser.add_argument('playground_config_file', help='playground config file')
copy_ipynb_parser.set_defaults(func=copy_ipynb)

def restart_ipython(args):
    stop_ipython(args)
    start_ipython(args)
add_simple_subparser(restart_ipython)

def restart_minecraft(args):
    stop_minecraft(args)
    start_minecraft(args)
add_simple_subparser(restart_minecraft)

def stop(args):
    stop_ipython(args)
    stop_minecraft(args)
add_simple_subparser(stop)

def start(args):
    start_minecraft(args)
    start_ipython(args)
add_simple_subparser(start)

def update(args):
    stop(args)
    create(args)
add_simple_subparser(update)

def update_raspberry_plugin(args):
    stop_minecraft(args)
    ssh_exec("rm " + pdir(args.playground_name) + "/minecraft-server/mods/* && cp minecraft-latest/mods/* " +
        pdir(args.playground_name) + "/minecraft-server/mods/")
    start_minecraft(args)
add_simple_subparser(update_raspberry_plugin)

def deploy_latest_spigot(args):
    playground_config = load_playground_config(args.playground_name, args.playground_config_file)
    stop_minecraft(args)
    download_latest_successfully_built_spigot_jar_from_circle_ci(playground_config)
    start_minecraft(args)
deploy_latest_spigot_parser = subparsers.add_parser("deploy-latest-spigot", help='{} foo')
deploy_latest_spigot_parser.add_argument('playground_config_file', help='json config for playgrounds')
deploy_latest_spigot_parser.set_defaults(func=deploy_latest_spigot)

def deploy_grpc_craft_plugin(args):
    playground_config = load_playground_config(args.playground_name, args.playground_config_file)
    stop_minecraft(args)
    download_latest_successfully_built_grpccraft_jar_from_circle_ci(playground_config, args.branch_name)
    start_minecraft(args)
deploy_grpc_craft_plugin_parser = subparsers.add_parser("deploy-grpc-craft-plugin", help='{} foo')
deploy_grpc_craft_plugin_parser.add_argument('playground_config_file', help='json config for playgrounds')
deploy_grpc_craft_plugin_parser.add_argument('branch_name', help='the grpc-craft branch of the artifact')
deploy_grpc_craft_plugin_parser.set_defaults(func=deploy_grpc_craft_plugin)

def destroy(args):
    exists(args)
    stop(args)
    ssh_exec("rm -rf {}".format(pdir(args.playground_name)))
add_simple_subparser(destroy)

def test_config_json(args):
    get_all_playground_config()
add_simple_subparser(test_config_json)

def test_rsync_destructive(args):
    rsync_destructive_be_careful_using_this("/tmp/foo1/", "/tmp/foo1/")
add_simple_subparser(test_rsync_destructive)

def write_crontab(args):
    crontab_lines = [
        # 7/2017 - spigot fits on a t2.small now, so i'm just going to let it run
        # indefinitely.
        # "55 10 * * * sudo shutdown -h now"
    ] # if instance is still running at 2:55am PT, shut it down.
    crontab_lines.append("@reboot /usr/bin/tmux new-session -s dstat -d '/usr/bin/dstat --time --load --mem --net  --io --swap --page --sys'")

    at_reboot_tmux_sessions = map(lambda path: "@reboot " + path, get_tmux_start_scripts())

    crontab_lines.extend(at_reboot_tmux_sessions)

    f = open("/tmp/crontab", 'w')
    f.write("\n".join(crontab_lines) + "\n")
    f.close()
    scp_r("/tmp/crontab", "new-crontab")
    ssh_exec("cat new-crontab | crontab -")
add_simple_subparser(write_crontab)

args = parser.parse_args()
args.func(args)

bb31363f8d9c3beac0f88a654d04f69f9ed1b080
<mask token>


def add_simple_subparser(f):
    command_name = f.__name__.replace('_', '-')
    p = subparsers.add_parser(command_name, help='{} help'.format(command_name)
        )
    p.set_defaults(func=f)


def exists(args):
    ssh_exec('file {}'.format(pdir(args.playground_name)))


<mask token>


def overlay(args):
    playground_config = load_playground_config(args.playground_name, args.
        playground_config_file)
    stage_overlay_files(playground_config)
    stage_generated_files(playground_config)
    create_and_link_shared2_dir(playground_config)
    create_and_link_share_file(playground_config)
    create_and_link_all_notebook_dir(playground_config)
    clean_remote_dirs(args.playground_name)
    upload_staged_files(args.playground_name)
    reset_basic_auth_password(args.playground_name, playground_config.
        web_password)
    prepare_client_log(args.playground_name)
    prepare_console_log(args.playground_name)
    set_directory_execute(args.playground_name)
    reload_nginx()
    write_crontab(args)
    write_rsyslog_conf(args)
    write_ipython_notebook_html()


<mask token>


def create(args):
    playground_config = load_playground_config(args.playground_name, args.
        playground_config_file)
    ssh_exec('mkdir -p {}'.format(pdir(args.playground_name)))
    copy_minecraft_server_files(args.playground_name)
    copy_spigot_server_files(playground_config)
    refresh_ipython(args)
    overlay(args)
    write_crontab(args)


<mask token>


def kill_if_listening_on_port(port_number):
    ssh_exec('fuser -vk {}/tcp || true'.format(port_number))


<mask token>


def stop_minecraft(args):
    tmux_kill(args.playground_name + '-mc')


<mask token>


def start_ipython(args):
    tmux_start(args.playground_name, '-py',
        'tmux_restart_ipython_notebook_server')


<mask token>


def minecraft_tunnel_jvm(args):
    playground_config = load_playground_config(args.playground_name, args.
        playground_config_file)
    exec_minecraft_tunnel_jvm(playground_config)


<mask token>


def refresh_ipython(args):
    ssh_exec_all(['mkdir -p {}'.format(ipython_data_dir(args.
        playground_name)), 'rm -rf {}/ipython-notebook-root/lib'.format(
        pdir(args.playground_name)),
        'mkdir -p {}/ipython-notebook-root/lib'.format(pdir(args.
        playground_name)), 'cp -r mcpi/mcpi {}/ipython-notebook-root/lib/'.
        format(pdir(args.playground_name)),
        'cp -r mcgamedata/mcgamedata {}/ipython-notebook-root/lib/'.format(
        pdir(args.playground_name)),
        'cp -r oogway/oogway {}/ipython-notebook-root/lib/'.format(pdir(
        args.playground_name)),
        'mkdir -p {}/ipython-notebook-root/lib/codeshare'.format(pdir(args.
        playground_name))])
    scp_r(this_dir + '/codeshare/extract.py',
        '{}/ipython-notebook-root/lib/codeshare/'.format(pdir(args.
        playground_name)))
    scp_r(this_dir + '/codeshare/ipynb_util.py',
        '{}/ipython-notebook-root/lib/codeshare/'.format(pdir(args.
        playground_name)))
    scp_r(this_dir + '/codeshare/document.py',
        '{}/ipython-notebook-root/lib/codeshare/'.format(pdir(args.
        playground_name)))


<mask token>


def copy_ipynb(args):
    playground_config = load_playground_config(args.playground_name, args.
        playground_config_file)
    source_playground_config = load_playground_config(args.
        source_playground_name, args.playground_config_file)
    quick_backup_ipython_notebooks(args.playground_name)
    existing_ipynb_wildcard = os.path.join(ipython_data_dir(args.
        playground_name), args.ipynb_wildcard + '.ipynb')
    ipynb_wildcard = os.path.join(ipython_data_dir(args.
        source_playground_name), args.ipynb_wildcard + '.ipynb')
    ipynbs = ssh_get('ls {}'.format(ipynb_wildcard)).strip().split('\n')
    if len(ipynbs) == 0:
        raise Exception('No ipython notebooks found matching {}'.format(
            ipynb_wildcard))
    else:
        print('will copy:')
        for ipynb in ipynbs:
            print(ipynb)
    ssh_exec('rm {} || true'.format(existing_ipynb_wildcard))
    ssh_exec('cp {} {}/{}'.format(ipynb_wildcard, ipython_data_dir(args.
        playground_name), args.dest_subdir))
    for ipynb in ipynbs:
        ipynb_relative_path = ipynb.replace(ipython_data_dir(args.
            source_playground_name) + '/', '')
        ipynb_relative_path = args.dest_subdir + '/' + ipynb_relative_path
        create_client_url_switch_scripts(source_playground_config,
            playground_config, ipynb_relative_path)
    ssh_exec('mkdir -p {}'.format(pdir(args.playground_name) + '/bin/url'))
    scp_r(DEST_URL_BIN_PREP_DIR + '/.', pdir(args.playground_name) + '/bin/url'
        )
    ssh_exec('mkdir -p {}'.format(pdir(args.source_playground_name) +
        '/bin/url'))
    scp_r(SOURCE_URL_BIN_PREP_DIR + '/.', pdir(args.source_playground_name) +
        '/bin/url')
    stage_overlay_files(source_playground_config)
    create_nginx_location_directives_for_bin_files(source_playground_config,
        get_bin_files_on_server_and_staged(source_playground_config), 
        OVERLAY_STAGING_DIR + '/nginx.conf', OVERLAY_STAGING_DIR +
        '/webroot/index.html')
    scp_r(OVERLAY_STAGING_DIR + '/nginx.conf', '{}/nginx.conf'.format(pdir(
        args.source_playground_name)))
    scp_r(OVERLAY_STAGING_DIR + '/webroot/index.html',
        '{}/webroot/index.html'.format(pdir(args.source_playground_name)))
    reload_nginx()


<mask token>


def restart_ipython(args):
    stop_ipython(args)
    start_ipython(args)


<mask token>


def restart_minecraft(args):
    stop_minecraft(args)
    start_minecraft(args)


<mask token>


def stop(args):
    stop_ipython(args)
    stop_minecraft(args)


<mask token>


def start(args):
    start_minecraft(args)
    start_ipython(args)


<mask token>


def update(args):
    stop(args)
    create(args)


<mask token>


def update_raspberry_plugin(args):
    stop_minecraft(args)
    ssh_exec('rm ' + pdir(args.playground_name) +
        '/minecraft-server/mods/* && cp minecraft-latest/mods/* ' + pdir(
        args.playground_name) + '/minecraft-server/mods/')
    start_minecraft(args)


<mask token>


def deploy_grpc_craft_plugin(args):
    playground_config = load_playground_config(args.playground_name, args.
        playground_config_file)
    stop_minecraft(args)
    download_latest_successfully_built_grpccraft_jar_from_circle_ci(
        playground_config, args.branch_name)
    start_minecraft(args)


<mask token>


def destroy(args):
    exists(args)
    stop(args)
    ssh_exec('rm -rf {}'.format(pdir(args.playground_name)))


<mask token>


def test_config_json(args):
    get_all_playground_config()


<mask token>


def write_crontab(args):
    crontab_lines = []
    crontab_lines.append(
        "@reboot /usr/bin/tmux new-session -s dstat -d '/usr/bin/dstat --time --load --mem --net  --io --swap --page --sys'"
        )
    at_reboot_tmux_sessions = map(lambda path: '@reboot ' + path,
        get_tmux_start_scripts())
    crontab_lines.extend(at_reboot_tmux_sessions)
    f = open('/tmp/crontab', 'w')
    f.write('\n'.join(crontab_lines) + '\n')
    f.close()
    scp_r('/tmp/crontab', 'new-crontab')
    ssh_exec('cat new-crontab | crontab -')


<mask token>

<mask token>


def add_simple_subparser(f):
    command_name = f.__name__.replace('_', '-')
    p = subparsers.add_parser(command_name, help='{} help'.format(command_name)
        )
    p.set_defaults(func=f)


def exists(args):
    ssh_exec('file {}'.format(pdir(args.playground_name)))


<mask token>


def test_overlay(args):
    playground_config = load_playground_config(args.playground_name, args.
        playground_config_file)
    stage_overlay_files(playground_config)
    stage_generated_files(playground_config)
    create_and_link_shared2_dir(playground_config)
    create_and_link_all_notebook_dir(playground_config)


<mask token>


def overlay(args):
    playground_config = load_playground_config(args.playground_name, args.
        playground_config_file)
    stage_overlay_files(playground_config)
    stage_generated_files(playground_config)
    create_and_link_shared2_dir(playground_config)
    create_and_link_share_file(playground_config)
    create_and_link_all_notebook_dir(playground_config)
    clean_remote_dirs(args.playground_name)
    upload_staged_files(args.playground_name)
    reset_basic_auth_password(args.playground_name, playground_config.
        web_password)
    prepare_client_log(args.playground_name)
    prepare_console_log(args.playground_name)
    set_directory_execute(args.playground_name)
    reload_nginx()
    write_crontab(args)
    write_rsyslog_conf(args)
    write_ipython_notebook_html()


<mask token>


def create(args):
    playground_config = load_playground_config(args.playground_name, args.
        playground_config_file)
    ssh_exec('mkdir -p {}'.format(pdir(args.playground_name)))
    copy_minecraft_server_files(args.playground_name)
    copy_spigot_server_files(playground_config)
    refresh_ipython(args)
    overlay(args)
    write_crontab(args)


<mask token>


def kill_if_listening_on_port(port_number):
    ssh_exec('fuser -vk {}/tcp || true'.format(port_number))


def stop_ipython(args):
    tmux_kill(args.playground_name + '-py')


<mask token>


def stop_minecraft(args):
    tmux_kill(args.playground_name + '-mc')


<mask token>


def start_ipython(args):
    tmux_start(args.playground_name, '-py',
        'tmux_restart_ipython_notebook_server')


<mask token>


def start_minecraft(args):
    tmux_start(args.playground_name, '-mc', 'tmux_restart_minecraft_server')


<mask token>


def minecraft_tunnel_jvm(args):
    playground_config = load_playground_config(args.playground_name, args.
        playground_config_file)
    exec_minecraft_tunnel_jvm(playground_config)


<mask token>


def refresh_ipython(args):
    ssh_exec_all(['mkdir -p {}'.format(ipython_data_dir(args.
        playground_name)), 'rm -rf {}/ipython-notebook-root/lib'.format(
        pdir(args.playground_name)),
        'mkdir -p {}/ipython-notebook-root/lib'.format(pdir(args.
        playground_name)), 'cp -r mcpi/mcpi {}/ipython-notebook-root/lib/'.
        format(pdir(args.playground_name)),
        'cp -r mcgamedata/mcgamedata {}/ipython-notebook-root/lib/'.format(
        pdir(args.playground_name)),
        'cp -r oogway/oogway {}/ipython-notebook-root/lib/'.format(pdir(
        args.playground_name)),
        'mkdir -p {}/ipython-notebook-root/lib/codeshare'.format(pdir(args.
        playground_name))])
    scp_r(this_dir + '/codeshare/extract.py',
        '{}/ipython-notebook-root/lib/codeshare/'.format(pdir(args.
        playground_name)))
    scp_r(this_dir + '/codeshare/ipynb_util.py',
        '{}/ipython-notebook-root/lib/codeshare/'.format(pdir(args.
        playground_name)))
    scp_r(this_dir + '/codeshare/document.py',
        '{}/ipython-notebook-root/lib/codeshare/'.format(pdir(args.
        playground_name)))


<mask token>


def copy_ipynb(args):
    playground_config = load_playground_config(args.playground_name, args.
        playground_config_file)
    source_playground_config = load_playground_config(args.
        source_playground_name, args.playground_config_file)
    quick_backup_ipython_notebooks(args.playground_name)
    existing_ipynb_wildcard = os.path.join(ipython_data_dir(args.
        playground_name), args.ipynb_wildcard + '.ipynb')
    ipynb_wildcard = os.path.join(ipython_data_dir(args.
        source_playground_name), args.ipynb_wildcard + '.ipynb')
    ipynbs = ssh_get('ls {}'.format(ipynb_wildcard)).strip().split('\n')
    if len(ipynbs) == 0:
        raise Exception('No ipython notebooks found matching {}'.format(
            ipynb_wildcard))
    else:
        print('will copy:')
        for ipynb in ipynbs:
            print(ipynb)
    ssh_exec('rm {} || true'.format(existing_ipynb_wildcard))
    ssh_exec('cp {} {}/{}'.format(ipynb_wildcard, ipython_data_dir(args.
        playground_name), args.dest_subdir))
    for ipynb in ipynbs:
        ipynb_relative_path = ipynb.replace(ipython_data_dir(args.
            source_playground_name) + '/', '')
        ipynb_relative_path = args.dest_subdir + '/' + ipynb_relative_path
        create_client_url_switch_scripts(source_playground_config,
            playground_config, ipynb_relative_path)
    ssh_exec('mkdir -p {}'.format(pdir(args.playground_name) + '/bin/url'))
    scp_r(DEST_URL_BIN_PREP_DIR + '/.', pdir(args.playground_name) + '/bin/url'
        )
    ssh_exec('mkdir -p {}'.format(pdir(args.source_playground_name) +
        '/bin/url'))
    scp_r(SOURCE_URL_BIN_PREP_DIR + '/.', pdir(args.source_playground_name) +
        '/bin/url')
    stage_overlay_files(source_playground_config)
    create_nginx_location_directives_for_bin_files(source_playground_config,
        get_bin_files_on_server_and_staged(source_playground_config), 
        OVERLAY_STAGING_DIR + '/nginx.conf', OVERLAY_STAGING_DIR +
        '/webroot/index.html')
    scp_r(OVERLAY_STAGING_DIR + '/nginx.conf', '{}/nginx.conf'.format(pdir(
        args.source_playground_name)))
    scp_r(OVERLAY_STAGING_DIR + '/webroot/index.html',
        '{}/webroot/index.html'.format(pdir(args.source_playground_name)))
    reload_nginx()


<mask token>


def restart_ipython(args):
    stop_ipython(args)
    start_ipython(args)


<mask token>


def restart_minecraft(args):
    stop_minecraft(args)
    start_minecraft(args)


<mask token>


def stop(args):
    stop_ipython(args)
    stop_minecraft(args)


<mask token>


def start(args):
    start_minecraft(args)
    start_ipython(args)


<mask token>


def update(args):
    stop(args)
    create(args)


<mask token>


def update_raspberry_plugin(args):
    stop_minecraft(args)
    ssh_exec('rm ' + pdir(args.playground_name) +
        '/minecraft-server/mods/* && cp minecraft-latest/mods/* ' + pdir(
        args.playground_name) + '/minecraft-server/mods/')
    start_minecraft(args)


<mask token>


def deploy_grpc_craft_plugin(args):
    playground_config = load_playground_config(args.playground_name, args.
        playground_config_file)
    stop_minecraft(args)
    download_latest_successfully_built_grpccraft_jar_from_circle_ci(
        playground_config, args.branch_name)
    start_minecraft(args)


<mask token>


def destroy(args):
    exists(args)
    stop(args)
    ssh_exec('rm -rf {}'.format(pdir(args.playground_name)))


<mask token>


def test_config_json(args):
    get_all_playground_config()


<mask token>


def write_crontab(args):
    crontab_lines = []
    crontab_lines.append(
        "@reboot /usr/bin/tmux new-session -s dstat -d '/usr/bin/dstat --time --load --mem --net  --io --swap --page --sys'"
        )
    at_reboot_tmux_sessions = map(lambda path: '@reboot ' + path,
        get_tmux_start_scripts())
    crontab_lines.extend(at_reboot_tmux_sessions)
    f = open('/tmp/crontab', 'w')
    f.write('\n'.join(crontab_lines) + '\n')
    f.close()
    scp_r('/tmp/crontab', 'new-crontab')
    ssh_exec('cat new-crontab | crontab -')


<mask token>

<mask token>


def add_simple_subparser(f):
    command_name = f.__name__.replace('_', '-')
    p = subparsers.add_parser(command_name, help='{} help'.format(command_name)
        )
    p.set_defaults(func=f)


def exists(args):
    ssh_exec('file {}'.format(pdir(args.playground_name)))


<mask token>


def status(args):
    ssh_exec('file {} || true'.format(pdir(args.playground_name)))


<mask token>


def test_overlay(args):
    playground_config = load_playground_config(args.playground_name, args.
        playground_config_file)
    stage_overlay_files(playground_config)
    stage_generated_files(playground_config)
    create_and_link_shared2_dir(playground_config)
    create_and_link_all_notebook_dir(playground_config)


<mask token>


def overlay(args):
    playground_config = load_playground_config(args.playground_name, args.
        playground_config_file)
    stage_overlay_files(playground_config)
    stage_generated_files(playground_config)
    create_and_link_shared2_dir(playground_config)
    create_and_link_share_file(playground_config)
    create_and_link_all_notebook_dir(playground_config)
    clean_remote_dirs(args.playground_name)
    upload_staged_files(args.playground_name)
    reset_basic_auth_password(args.playground_name, playground_config.
        web_password)
    prepare_client_log(args.playground_name)
    prepare_console_log(args.playground_name)
    set_directory_execute(args.playground_name)
    reload_nginx()
    write_crontab(args)
    write_rsyslog_conf(args)
    write_ipython_notebook_html()


<mask token>


def create(args):
    playground_config = load_playground_config(args.playground_name, args.
        playground_config_file)
    ssh_exec('mkdir -p {}'.format(pdir(args.playground_name)))
    copy_minecraft_server_files(args.playground_name)
    copy_spigot_server_files(playground_config)
    refresh_ipython(args)
    overlay(args)
    write_crontab(args)


<mask token>


def kill_if_listening_on_port(port_number):
    ssh_exec('fuser -vk {}/tcp || true'.format(port_number))


def stop_ipython(args):
    tmux_kill(args.playground_name + '-py')


<mask token>


def stop_minecraft(args):
    tmux_kill(args.playground_name + '-mc')


<mask token>


def start_ipython(args):
    tmux_start(args.playground_name, '-py',
        'tmux_restart_ipython_notebook_server')


<mask token>


def start_minecraft(args):
    tmux_start(args.playground_name, '-mc', 'tmux_restart_minecraft_server')


<mask token>


def minecraft_tunnel_jvm(args):
    playground_config = load_playground_config(args.playground_name, args.
        playground_config_file)
    exec_minecraft_tunnel_jvm(playground_config)


<mask token>


def refresh_ipython(args):
    ssh_exec_all(['mkdir -p {}'.format(ipython_data_dir(args.
        playground_name)), 'rm -rf {}/ipython-notebook-root/lib'.format(
        pdir(args.playground_name)),
        'mkdir -p {}/ipython-notebook-root/lib'.format(pdir(args.
        playground_name)), 'cp -r mcpi/mcpi {}/ipython-notebook-root/lib/'.
        format(pdir(args.playground_name)),
        'cp -r mcgamedata/mcgamedata {}/ipython-notebook-root/lib/'.format(
        pdir(args.playground_name)),
        'cp -r oogway/oogway {}/ipython-notebook-root/lib/'.format(pdir(
        args.playground_name)),
        'mkdir -p {}/ipython-notebook-root/lib/codeshare'.format(pdir(args.
        playground_name))])
    scp_r(this_dir + '/codeshare/extract.py',
        '{}/ipython-notebook-root/lib/codeshare/'.format(pdir(args.
        playground_name)))
    scp_r(this_dir + '/codeshare/ipynb_util.py',
        '{}/ipython-notebook-root/lib/codeshare/'.format(pdir(args.
        playground_name)))
    scp_r(this_dir + '/codeshare/document.py',
        '{}/ipython-notebook-root/lib/codeshare/'.format(pdir(args.
        playground_name)))


<mask token>


def copy_ipynb(args):
    playground_config = load_playground_config(args.playground_name, args.
        playground_config_file)
    source_playground_config = load_playground_config(args.
        source_playground_name, args.playground_config_file)
    quick_backup_ipython_notebooks(args.playground_name)
    existing_ipynb_wildcard = os.path.join(ipython_data_dir(args.
        playground_name), args.ipynb_wildcard + '.ipynb')
    ipynb_wildcard = os.path.join(ipython_data_dir(args.
        source_playground_name), args.ipynb_wildcard + '.ipynb')
    ipynbs = ssh_get('ls {}'.format(ipynb_wildcard)).strip().split('\n')
    if len(ipynbs) == 0:
        raise Exception('No ipython notebooks found matching {}'.format(
            ipynb_wildcard))
    else:
        print('will copy:')
        for ipynb in ipynbs:
            print(ipynb)
    ssh_exec('rm {} || true'.format(existing_ipynb_wildcard))
    ssh_exec('cp {} {}/{}'.format(ipynb_wildcard, ipython_data_dir(args.
        playground_name), args.dest_subdir))
    for ipynb in ipynbs:
        ipynb_relative_path = ipynb.replace(ipython_data_dir(args.
            source_playground_name) + '/', '')
        ipynb_relative_path = args.dest_subdir + '/' + ipynb_relative_path
        create_client_url_switch_scripts(source_playground_config,
            playground_config, ipynb_relative_path)
    ssh_exec('mkdir -p {}'.format(pdir(args.playground_name) + '/bin/url'))
    scp_r(DEST_URL_BIN_PREP_DIR + '/.', pdir(args.playground_name) + '/bin/url'
        )
    ssh_exec('mkdir -p {}'.format(pdir(args.source_playground_name) +
        '/bin/url'))
    scp_r(SOURCE_URL_BIN_PREP_DIR + '/.', pdir(args.source_playground_name) +
        '/bin/url')
    stage_overlay_files(source_playground_config)
    create_nginx_location_directives_for_bin_files(source_playground_config,
        get_bin_files_on_server_and_staged(source_playground_config), 
        OVERLAY_STAGING_DIR + '/nginx.conf', OVERLAY_STAGING_DIR +
        '/webroot/index.html')
    scp_r(OVERLAY_STAGING_DIR + '/nginx.conf', '{}/nginx.conf'.format(pdir(
        args.source_playground_name)))
    scp_r(OVERLAY_STAGING_DIR + '/webroot/index.html',
        '{}/webroot/index.html'.format(pdir(args.source_playground_name)))
    reload_nginx()


<mask token>


def restart_ipython(args):
    stop_ipython(args)
    start_ipython(args)


<mask token>


def restart_minecraft(args):
    stop_minecraft(args)
    start_minecraft(args)


<mask token>


def stop(args):
    stop_ipython(args)
    stop_minecraft(args)


<mask token>


def start(args):
    start_minecraft(args)
    start_ipython(args)


<mask token>


def update(args):
    stop(args)
    create(args)


<mask token>


def update_raspberry_plugin(args):
    stop_minecraft(args)
    ssh_exec('rm ' + pdir(args.playground_name) +
        '/minecraft-server/mods/* && cp minecraft-latest/mods/* ' + pdir(
        args.playground_name) + '/minecraft-server/mods/')
    start_minecraft(args)


<mask token>


def deploy_grpc_craft_plugin(args):
    playground_config = load_playground_config(args.playground_name, args.
        playground_config_file)
    stop_minecraft(args)
    download_latest_successfully_built_grpccraft_jar_from_circle_ci(
        playground_config, args.branch_name)
    start_minecraft(args)


<mask token>


def destroy(args):
    exists(args)
    stop(args)
    ssh_exec('rm -rf {}'.format(pdir(args.playground_name)))


<mask token>


def test_config_json(args):
    get_all_playground_config()


<mask token>


def write_crontab(args):
    crontab_lines = []
    crontab_lines.append(
        "@reboot /usr/bin/tmux new-session -s dstat -d '/usr/bin/dstat --time --load --mem --net  --io --swap --page --sys'"
        )
    at_reboot_tmux_sessions = map(lambda path: '@reboot ' + path,
        get_tmux_start_scripts())
    crontab_lines.extend(at_reboot_tmux_sessions)
    f = open('/tmp/crontab', 'w')
    f.write('\n'.join(crontab_lines) + '\n')
    f.close()
    scp_r('/tmp/crontab', 'new-crontab')
    ssh_exec('cat new-crontab | crontab -')


<mask token>

<mask token>
sys.path.append(oogway_relative_dir)
<mask token>
parser.add_argument('playground_name', type=str, help='help TODO')
<mask token>


def add_simple_subparser(f):
    command_name = f.__name__.replace('_', '-')
    p = subparsers.add_parser(command_name, help='{} help'.format(command_name)
        )
    p.set_defaults(func=f)


def exists(args):
    ssh_exec('file {}'.format(pdir(args.playground_name)))


add_simple_subparser(exists)


def status(args):
    ssh_exec('file {} || true'.format(pdir(args.playground_name)))


add_simple_subparser(status)


def test_overlay(args):
    playground_config = load_playground_config(args.playground_name, args.
        playground_config_file)
    stage_overlay_files(playground_config)
    stage_generated_files(playground_config)
    create_and_link_shared2_dir(playground_config)
    create_and_link_all_notebook_dir(playground_config)


<mask token>
test_overlay_parser.add_argument('playground_config_file', help=
    'json config for playgrounds')
test_overlay_parser.set_defaults(func=test_overlay)


def overlay(args):
    playground_config = load_playground_config(args.playground_name, args.
        playground_config_file)
    stage_overlay_files(playground_config)
    stage_generated_files(playground_config)
    create_and_link_shared2_dir(playground_config)
    create_and_link_share_file(playground_config)
    create_and_link_all_notebook_dir(playground_config)
    clean_remote_dirs(args.playground_name)
    upload_staged_files(args.playground_name)
    reset_basic_auth_password(args.playground_name, playground_config.
        web_password)
    prepare_client_log(args.playground_name)
    prepare_console_log(args.playground_name)
    set_directory_execute(args.playground_name)
    reload_nginx()
    write_crontab(args)
    write_rsyslog_conf(args)
    write_ipython_notebook_html()


<mask token>
overlay_parser.add_argument('playground_config_file', help=
    'json config for playgrounds')
overlay_parser.set_defaults(func=overlay)


def create(args):
    playground_config = load_playground_config(args.playground_name, args.
        playground_config_file)
    ssh_exec('mkdir -p {}'.format(pdir(args.playground_name)))
    copy_minecraft_server_files(args.playground_name)
    copy_spigot_server_files(playground_config)
    refresh_ipython(args)
    overlay(args)
    write_crontab(args)


<mask token>
create_parser.add_argument('playground_config_file', help=
    'json config for playgrounds')
create_parser.set_defaults(func=create)


def kill_if_listening_on_port(port_number):
    ssh_exec('fuser -vk {}/tcp || true'.format(port_number))


def stop_ipython(args):
    tmux_kill(args.playground_name + '-py')


add_simple_subparser(stop_ipython)


def stop_minecraft(args):
    tmux_kill(args.playground_name + '-mc')


add_simple_subparser(stop_minecraft)


def start_ipython(args):
    tmux_start(args.playground_name, '-py',
        'tmux_restart_ipython_notebook_server')


add_simple_subparser(start_ipython)


def start_minecraft(args):
    tmux_start(args.playground_name, '-mc', 'tmux_restart_minecraft_server')


add_simple_subparser(start_minecraft)


def minecraft_tunnel_jvm(args):
    playground_config = load_playground_config(args.playground_name, args.
        playground_config_file)
    exec_minecraft_tunnel_jvm(playground_config)


<mask token>
exec_minecraft_tunnel_jvm_parser.add_argument('playground_config_file',
    help='json config for playgrounds')
exec_minecraft_tunnel_jvm_parser.set_defaults(func=minecraft_tunnel_jvm)


def refresh_ipython(args):
    ssh_exec_all(['mkdir -p {}'.format(ipython_data_dir(args.
        playground_name)), 'rm -rf {}/ipython-notebook-root/lib'.format(
        pdir(args.playground_name)),
        'mkdir -p {}/ipython-notebook-root/lib'.format(pdir(args.
        playground_name)), 'cp -r mcpi/mcpi {}/ipython-notebook-root/lib/'.
        format(pdir(args.playground_name)),
        'cp -r mcgamedata/mcgamedata {}/ipython-notebook-root/lib/'.format(
        pdir(args.playground_name)),
        'cp -r oogway/oogway {}/ipython-notebook-root/lib/'.format(pdir(
        args.playground_name)),
        'mkdir -p {}/ipython-notebook-root/lib/codeshare'.format(pdir(args.
        playground_name))])
    scp_r(this_dir + '/codeshare/extract.py',
        '{}/ipython-notebook-root/lib/codeshare/'.format(pdir(args.
        playground_name)))
    scp_r(this_dir + '/codeshare/ipynb_util.py',
        '{}/ipython-notebook-root/lib/codeshare/'.format(pdir(args.
        playground_name)))
    scp_r(this_dir + '/codeshare/document.py',
        '{}/ipython-notebook-root/lib/codeshare/'.format(pdir(args.
        playground_name)))


add_simple_subparser(refresh_ipython)


def copy_ipynb(args):
    playground_config = load_playground_config(args.playground_name, args.
        playground_config_file)
    source_playground_config = load_playground_config(args.
        source_playground_name, args.playground_config_file)
    quick_backup_ipython_notebooks(args.playground_name)
    existing_ipynb_wildcard = os.path.join(ipython_data_dir(args.
        playground_name), args.ipynb_wildcard + '.ipynb')
    ipynb_wildcard = os.path.join(ipython_data_dir(args.
        source_playground_name), args.ipynb_wildcard + '.ipynb')
    ipynbs = ssh_get('ls {}'.format(ipynb_wildcard)).strip().split('\n')
    if len(ipynbs) == 0:
        raise Exception('No ipython notebooks found matching {}'.format(
            ipynb_wildcard))
    else:
        print('will copy:')
        for ipynb in ipynbs:
            print(ipynb)
    ssh_exec('rm {} || true'.format(existing_ipynb_wildcard))
    ssh_exec('cp {} {}/{}'.format(ipynb_wildcard, ipython_data_dir(args.
        playground_name), args.dest_subdir))
    for ipynb in ipynbs:
        ipynb_relative_path = ipynb.replace(ipython_data_dir(args.
            source_playground_name) + '/', '')
        ipynb_relative_path = args.dest_subdir + '/' + ipynb_relative_path
        create_client_url_switch_scripts(source_playground_config,
            playground_config, ipynb_relative_path)
    ssh_exec('mkdir -p {}'.format(pdir(args.playground_name) + '/bin/url'))
    scp_r(DEST_URL_BIN_PREP_DIR + '/.', pdir(args.playground_name) + '/bin/url'
        )
    ssh_exec('mkdir -p {}'.format(pdir(args.source_playground_name) +
        '/bin/url'))
    scp_r(SOURCE_URL_BIN_PREP_DIR + '/.', pdir(args.source_playground_name) +
        '/bin/url')
    stage_overlay_files(source_playground_config)
    create_nginx_location_directives_for_bin_files(source_playground_config,
        get_bin_files_on_server_and_staged(source_playground_config), 
        OVERLAY_STAGING_DIR + '/nginx.conf', OVERLAY_STAGING_DIR +
        '/webroot/index.html')
    scp_r(OVERLAY_STAGING_DIR + '/nginx.conf', '{}/nginx.conf'.format(pdir(
        args.source_playground_name)))
    scp_r(OVERLAY_STAGING_DIR + '/webroot/index.html',
        '{}/webroot/index.html'.format(pdir(args.source_playground_name)))
    reload_nginx()


<mask token>
copy_ipynb_parser.add_argument('source_playground_name', help=
    'the playground that has the ipython notebook(s)')
copy_ipynb_parser.add_argument('ipynb_wildcard', help=
    'wildcard that matches ipython notebook(s)')
copy_ipynb_parser.add_argument('dest_subdir', help='destination subdirectory')
copy_ipynb_parser.add_argument('playground_config_file', help=
    'playground config file')
copy_ipynb_parser.set_defaults(func=copy_ipynb)


def restart_ipython(args):
    stop_ipython(args)
    start_ipython(args)


add_simple_subparser(restart_ipython)


def restart_minecraft(args):
    stop_minecraft(args)
    start_minecraft(args)


add_simple_subparser(restart_minecraft)


def stop(args):
    stop_ipython(args)
    stop_minecraft(args)


add_simple_subparser(stop)


def start(args):
    start_minecraft(args)
    start_ipython(args)


add_simple_subparser(start)


def update(args):
    stop(args)
    create(args)


add_simple_subparser(update)


def update_raspberry_plugin(args):
    stop_minecraft(args)
    ssh_exec('rm ' + pdir(args.playground_name) +
        '/minecraft-server/mods/* && cp minecraft-latest/mods/* ' + pdir(
        args.playground_name) + '/minecraft-server/mods/')
    start_minecraft(args)


add_simple_subparser(update_raspberry_plugin)


def deploy_latest_spigot(args):
    playground_config = load_playground_config(args.playground_name, args.
        playground_config_file)
    stop_minecraft(args)
    download_latest_successfully_built_spigot_jar_from_circle_ci(
        playground_config)
    start_minecraft(args)


<mask token>
deploy_latest_spigot_parser.add_argument('playground_config_file', help=
    'json config for playgrounds')
deploy_latest_spigot_parser.set_defaults(func=deploy_latest_spigot)


def deploy_grpc_craft_plugin(args):
    playground_config = load_playground_config(args.playground_name, args.
        playground_config_file)
    stop_minecraft(args)
    download_latest_successfully_built_grpccraft_jar_from_circle_ci(
        playground_config, args.branch_name)
    start_minecraft(args)


<mask token>
deploy_grpc_craft_plugin_parser.add_argument('playground_config_file', help
    ='json config for playgrounds')
deploy_grpc_craft_plugin_parser.add_argument('branch_name', help=
    'the grpc-craft branch of the artifact')
deploy_grpc_craft_plugin_parser.set_defaults(func=deploy_grpc_craft_plugin)


def destroy(args):
    exists(args)
    stop(args)
    ssh_exec('rm -rf {}'.format(pdir(args.playground_name)))


add_simple_subparser(destroy)


def test_config_json(args):
    get_all_playground_config()


add_simple_subparser(test_config_json)


def test_rsync_destructive(args):
    rsync_destructive_be_careful_using_this('/tmp/foo1/', '/tmp/foo1/')


add_simple_subparser(test_rsync_destructive)


def write_crontab(args):
    crontab_lines = []
    crontab_lines.append(
        "@reboot /usr/bin/tmux new-session -s dstat -d '/usr/bin/dstat --time --load --mem --net  --io --swap --page --sys'"
        )
    at_reboot_tmux_sessions = map(lambda path: '@reboot ' + path,
        get_tmux_start_scripts())
    crontab_lines.extend(at_reboot_tmux_sessions)
    f = open('/tmp/crontab', 'w')
    f.write('\n'.join(crontab_lines) + '\n')
    f.close()
    scp_r('/tmp/crontab', 'new-crontab')
    ssh_exec('cat new-crontab | crontab -')


add_simple_subparser(write_crontab)
<mask token>
args.func(args)

#!/usr/bin/env python

import sys
import argparse
import os.path
import os

from lib import const
from lib.core import ssh_exec, ssh_exec_all, ssh_get, scp_r, scp_r_remote_to_local
from lib.playground_config import PlaygroundConfig, load_playground_config

this_dir = os.path.dirname(os.path.realpath(__file__))
oogway_relative_dir = os.path.join(this_dir, "../oogway")
sys.path.append(oogway_relative_dir)

from lib.playground.ipython import *
from lib.playground.nginx import *
from lib.playground.process_management import *
from lib.playground.rsyslog import *
from lib.playground.spigot_grpc import *
from lib.playground.sponge_mcpi import *
from lib.playground.staging_files import *
from lib.playground.teleport import *
from lib.playground.util import *
from lib.playground.windows_client import *

parser = argparse.ArgumentParser()
parser.add_argument('playground_name', type=str, help='help TODO')
subparsers = parser.add_subparsers(help='sub-command help')

def add_simple_subparser(f):
    command_name = f.__name__.replace("_", "-")
    p = subparsers.add_parser(command_name, help='{} help'.format(command_name))
    p.set_defaults(func=f)

def exists(args):
    ssh_exec("file {}".format(pdir(args.playground_name)))
add_simple_subparser(exists)

def status(args):
    # TODO: should be better
    ssh_exec("file {} || true".format(pdir(args.playground_name)))
add_simple_subparser(status)

def test_overlay(args):
    playground_config = load_playground_config(args.playground_name, args.playground_config_file)
    stage_overlay_files(playground_config)
    stage_generated_files(playground_config)
    create_and_link_shared2_dir(playground_config)
    create_and_link_all_notebook_dir(playground_config)
test_overlay_parser = subparsers.add_parser("test-overlay", help='{} overlay')
test_overlay_parser.add_argument('playground_config_file', help='json config for playgrounds')
test_overlay_parser.set_defaults(func=test_overlay)

def overlay(args):
    playground_config = load_playground_config(args.playground_name, args.playground_config_file)
    stage_overlay_files(playground_config)
    stage_generated_files(playground_config)
    create_and_link_shared2_dir(playground_config)
    create_and_link_share_file(playground_config)
    create_and_link_all_notebook_dir(playground_config)
    clean_remote_dirs(args.playground_name)
    upload_staged_files(args.playground_name)
    reset_basic_auth_password(args.playground_name, playground_config.web_password)
    prepare_client_log(args.playground_name)
    prepare_console_log(args.playground_name)
    set_directory_execute(args.playground_name) # something was stripping execute...um not sure what.
    reload_nginx()
    write_crontab(args)
    write_rsyslog_conf(args)
    write_ipython_notebook_html()
overlay_parser = subparsers.add_parser("overlay", help='{} overlay')
overlay_parser.add_argument('playground_config_file', help='json config for playgrounds')
overlay_parser.set_defaults(func=overlay)

def create(args):
    playground_config = load_playground_config(args.playground_name, args.playground_config_file)
    ssh_exec("mkdir -p {}".format(pdir(args.playground_name)))
    copy_minecraft_server_files(args.playground_name)
    copy_spigot_server_files(playground_config)
    refresh_ipython(args)
    overlay(args)
    write_crontab(args)
create_parser = subparsers.add_parser("create", help='{} overlay')
create_parser.add_argument('playground_config_file', help='json config for playgrounds')
create_parser.set_defaults(func=create)

def kill_if_listening_on_port(port_number):
    ssh_exec("fuser -vk {}/tcp || true".format(port_number))

def stop_ipython(args):
    tmux_kill(args.playground_name + "-py")
add_simple_subparser(stop_ipython)

def stop_minecraft(args):
    tmux_kill(args.playground_name + "-mc")
add_simple_subparser(stop_minecraft)

def start_ipython(args):
    tmux_start(args.playground_name, "-py", "tmux_restart_ipython_notebook_server")
add_simple_subparser(start_ipython)

def start_minecraft(args):
    tmux_start(args.playground_name, "-mc", "tmux_restart_minecraft_server")
add_simple_subparser(start_minecraft)

def minecraft_tunnel_jvm(args):
    playground_config = load_playground_config(args.playground_name, args.playground_config_file)
    exec_minecraft_tunnel_jvm(playground_config)
exec_minecraft_tunnel_jvm_parser = subparsers.add_parser("minecraft-tunnel-jvm", help='{} minecraft-tunnel-jvm')
exec_minecraft_tunnel_jvm_parser.add_argument('playground_config_file', help='json config for playgrounds')
exec_minecraft_tunnel_jvm_parser.set_defaults(func=minecraft_tunnel_jvm)

def refresh_ipython(args):
    ssh_exec_all([
        "mkdir -p {}".format(ipython_data_dir(args.playground_name)),
        "rm -rf {}/ipython-notebook-root/lib".format(pdir(args.playground_name)),
        "mkdir -p {}/ipython-notebook-root/lib".format(pdir(args.playground_name)),
        "cp -r mcpi/mcpi {}/ipython-notebook-root/lib/".format(pdir(args.playground_name)),
        "cp -r mcgamedata/mcgamedata {}/ipython-notebook-root/lib/".format(pdir(args.playground_name)),
        "cp -r oogway/oogway {}/ipython-notebook-root/lib/".format(pdir(args.playground_name)),
        "mkdir -p {}/ipython-notebook-root/lib/codeshare".format(pdir(args.playground_name))
    ])
    scp_r(this_dir + "/codeshare/extract.py", "{}/ipython-notebook-root/lib/codeshare/".format(pdir(args.playground_name)))
    scp_r(this_dir + "/codeshare/ipynb_util.py", "{}/ipython-notebook-root/lib/codeshare/".format(pdir(args.playground_name)))
    scp_r(this_dir + "/codeshare/document.py", "{}/ipython-notebook-root/lib/codeshare/".format(pdir(args.playground_name)))
add_simple_subparser(refresh_ipython)

def copy_ipynb(args):
    playground_config = load_playground_config(args.playground_name, args.playground_config_file)
    source_playground_config = load_playground_config(args.source_playground_name, args.playground_config_file)
    quick_backup_ipython_notebooks(args.playground_name)
    existing_ipynb_wildcard = os.path.join(ipython_data_dir(args.playground_name), args.ipynb_wildcard + ".ipynb")
    ipynb_wildcard = os.path.join(ipython_data_dir(args.source_playground_name), args.ipynb_wildcard + ".ipynb")
    ipynbs = ssh_get("ls {}".format(ipynb_wildcard)).strip().split("\n")

    if len(ipynbs) == 0:
        raise Exception("No ipython notebooks found matching {}".format(ipynb_wildcard))
    else:
        print("will copy:")
        for ipynb in ipynbs:
            print(ipynb)
    ssh_exec("rm {} || true".format(existing_ipynb_wildcard))
    ssh_exec("cp {} {}/{}".format(ipynb_wildcard, ipython_data_dir(args.playground_name), args.dest_subdir))

    for ipynb in ipynbs:
        ipynb_relative_path = ipynb.replace(ipython_data_dir(args.source_playground_name) + "/", "")
        ipynb_relative_path = args.dest_subdir + "/" + ipynb_relative_path
        create_client_url_switch_scripts(source_playground_config, playground_config, ipynb_relative_path)

    ssh_exec("mkdir -p {}".format(pdir(args.playground_name) + "/bin/url"))
    scp_r(DEST_URL_BIN_PREP_DIR + "/.", pdir(args.playground_name) + "/bin/url")
    ssh_exec("mkdir -p {}".format(pdir(args.source_playground_name) + "/bin/url"))
    scp_r(SOURCE_URL_BIN_PREP_DIR + "/.", pdir(args.source_playground_name) + "/bin/url")

    stage_overlay_files(source_playground_config)
    create_nginx_location_directives_for_bin_files(
        source_playground_config,
        get_bin_files_on_server_and_staged(source_playground_config),
        OVERLAY_STAGING_DIR + "/nginx.conf",
        OVERLAY_STAGING_DIR + "/webroot/index.html")
    scp_r(OVERLAY_STAGING_DIR + "/nginx.conf", "{}/nginx.conf".format(pdir(args.source_playground_name)))
    scp_r(OVERLAY_STAGING_DIR + "/webroot/index.html", "{}/webroot/index.html".format(pdir(args.source_playground_name)))
    reload_nginx()

copy_ipynb_parser = subparsers.add_parser("copy-ipynb", help='{} copy-ipynb')
copy_ipynb_parser.add_argument('source_playground_name', help='the playground that has the ipython notebook(s)')
copy_ipynb_parser.add_argument('ipynb_wildcard', help='wildcard that matches ipython notebook(s)')
copy_ipynb_parser.add_argument('dest_subdir', help='destination subdirectory')
copy_ipynb_parser.add_argument('playground_config_file', help='playground config file')
copy_ipynb_parser.set_defaults(func=copy_ipynb)

def restart_ipython(args):
    stop_ipython(args)
    start_ipython(args)
add_simple_subparser(restart_ipython)

def restart_minecraft(args):
    stop_minecraft(args)
    start_minecraft(args)
add_simple_subparser(restart_minecraft)

def stop(args):
    stop_ipython(args)
    stop_minecraft(args)
add_simple_subparser(stop)

def start(args):
    start_minecraft(args)
    start_ipython(args)
add_simple_subparser(start)

def update(args):
    stop(args)
    create(args)
add_simple_subparser(update)

def update_raspberry_plugin(args):
    stop_minecraft(args)
    ssh_exec("rm " + pdir(args.playground_name) + "/minecraft-server/mods/* && cp minecraft-latest/mods/* " +
        pdir(args.playground_name) + "/minecraft-server/mods/")
    start_minecraft(args)
add_simple_subparser(update_raspberry_plugin)

def deploy_latest_spigot(args):
    playground_config = load_playground_config(args.playground_name, args.playground_config_file)
    stop_minecraft(args)
    download_latest_successfully_built_spigot_jar_from_circle_ci(playground_config)
    start_minecraft(args)
deploy_latest_spigot_parser = subparsers.add_parser("deploy-latest-spigot", help='{} foo')
deploy_latest_spigot_parser.add_argument('playground_config_file', help='json config for playgrounds')
deploy_latest_spigot_parser.set_defaults(func=deploy_latest_spigot)

def deploy_grpc_craft_plugin(args):
    playground_config = load_playground_config(args.playground_name, args.playground_config_file)
    stop_minecraft(args)
    download_latest_successfully_built_grpccraft_jar_from_circle_ci(playground_config, args.branch_name)
    start_minecraft(args)
deploy_grpc_craft_plugin_parser = subparsers.add_parser("deploy-grpc-craft-plugin", help='{} foo')
deploy_grpc_craft_plugin_parser.add_argument('playground_config_file', help='json config for playgrounds')
deploy_grpc_craft_plugin_parser.add_argument('branch_name', help='the grpc-craft branch of the artifact')
deploy_grpc_craft_plugin_parser.set_defaults(func=deploy_grpc_craft_plugin)

def destroy(args):
    exists(args)
    stop(args)
    ssh_exec("rm -rf {}".format(pdir(args.playground_name)))
add_simple_subparser(destroy)

def test_config_json(args):
    get_all_playground_config()
add_simple_subparser(test_config_json)

def test_rsync_destructive(args):
    rsync_destructive_be_careful_using_this("/tmp/foo1/", "/tmp/foo1/")
add_simple_subparser(test_rsync_destructive)

def write_crontab(args):
    crontab_lines = [
        # 7/2017 - spigot fits on a t2.small now, so i'm just going to let it run
        # indefinitely.
        # "55 10 * * * sudo shutdown -h now"
    ] # if instance is still running at 2:55am PT, shut it down.
    crontab_lines.append("@reboot /usr/bin/tmux new-session -s dstat -d '/usr/bin/dstat --time --load --mem --net  --io --swap --page --sys'")

    at_reboot_tmux_sessions = map(lambda path: "@reboot " + path, get_tmux_start_scripts())

    crontab_lines.extend(at_reboot_tmux_sessions)

    f = open("/tmp/crontab", 'w')
    f.write("\n".join(crontab_lines) + "\n")
    f.close()
    scp_r("/tmp/crontab", "new-crontab")
    ssh_exec("cat new-crontab | crontab -")
add_simple_subparser(write_crontab)

args = parser.parse_args()
args.func(args)
