"""Battlefield 2 server script for executing unauthorized commands"""

import new
import sys

import default
import host
from bf2 import g_debug


def rcmd_exec(self, ctx, cmd):
    # Could the command crash the server?
    if 'pythonHost.reinitialize' in cmd.lower():
        ctx.write(
            'Executing this command through uexec.py will crash the '
            'server!\nTry adding it to sv.configFile manually and then '
            'running sv.load!\n'
        )
    # Try executing the command
    else:
        results = host.rcon_invoke(cmd)

        # Is the command restricted?
        if 'Unauthorised method!' in results:
            ctx.write(results)
        else:
            ctx.write(
                'Note: Unauthorised method! Results will not be printed!\n'
            )

            # Get value of sv.configFile and back it up
            config_path = host.rcon_invoke('sv.configFile').strip('\r\n')

            try:
                config_file = open(config_path, 'r')
                config_backup = config_file.read()
                config_file.close()
            except:
                ctx.write(''.join([
                    'Failed to backup sv.configFile\n',
                    str(sys.exc_info()[0]).split('.')[-1],
                    ': ',
                    str(sys.exc_info()[1]),
                    '\n'
                ]))

            # Save current settings and write command to sv.configFile
            host.rcon_invoke('sv.save')

            try:
                config_file = file(config_path, 'a')
                config_file.write('\n')
                config_file.write(cmd)
                config_file.close()
            except:
                ctx.write(''.join([
                    'Failed to add command to sv.configFile\n',
                    str(sys.exc_info()[0]).split('.')[-1],
                    ': ',
                    str(sys.exc_info()[1]),
                    '\n'
                ]))

            # Try sv.load
            try:
                retval = int(host.rcon_invoke('sv.load').strip('\r\n'))
                if retval != 1:
                    raise ValueError()
            except ValueError:
                ctx.write('Failed to load sv.configFile')

            # Revert sv.configFile
            host.rcon_invoke('sv.save')

            try:
                config_file = file(config_path, 'w')
                config_file.write(config_Backup)
                config_file.close()
            except:
                ctx.write(''.join([
                    'Failed to revert sv.configFile\n',
                    str(sys.exc_info()[0]).split('.')[-1],
                    ': ',
                    str(sys.exc_info()[1]),
                    '\n'
                ]))


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

    bound_method = new.instancemethod(
        rcmd_exec,
        default.server,
        default.AdminServer
    )
    default.AdminServer.rcmd_exec = bound_method
    default.server.rcon_cmds['exec'] = default.AdminServer.rcmd_exec

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