"""Battlefield 2 server script that allows code evaluation in the console"""

import sys
import new

import bf2
import host
import game
import default
import standard_admin
from bf2 import g_debug


def rcmd_eval(self, ctx, cmd):
    try:
        eval(compile(cmd, '<string>', 'exec'))
    except:
        ctx.write(''.join([
            str(sys.exc_info()[0]).split('.')[-1],
            ': ',
            str(sys.exc_info()[1]),
            '\n'
        ]))


def init():
    if g_debug:
        print 'Initializing eval script'

    bound_method = new.instancemethod(
        rcmd_eval,
        default.server,
        default.AdminServer
    )
    default.AdminServer.rcmd_eval = bound_method
    default.server.rcon_cmds['eval'] = default.AdminServer.rcmd_eval

    host.rcon_invoke('echo "eval.py loaded"')
