################################################################################
#
# shell.py
#
# This module has a single command in it: shell. This command allows admins to
# execute shell commands from inside the mud. If the user does not explicity
# specify that the output should be redirected to some file, the command will
# redirect the output to a special file and then read its contents and page the
# contents to the user of the command. Although this is a very useful command,
# it is not a part of the default NakedMud release because some mud owners will
# certainly not want all of their mud admins to have this sort of power. Fair
# enough.
#
# To install this module, simply drop it in lib/pymodules and reboot your mud.
# Optionally, you can load the module into the game without rebooting by using
# the "pyload shell" command.
#
# This module requires a minimum NakedMud v2.6, for access to the page method.
# If you are not running v2.6, you will have to give the Python wrapper for
# characters access to the socket page function.
#
################################################################################

from os  import system
from mud import add_cmd

#
# Executes a command in the shell. If a redirection of output isn't specified,
# then page the output of the command to the person using the command 
def cmd_shell(ch, cmd, arg):
    # make sure we have a command to execute
    if arg == '':
        ch.send("Which shell command would you like to execute?")
    else:
        # if we're not already redirecting output, do so, and page it to us
        page_out = (arg.count(">") == 0)
        if page_out:
            arg = arg + " &> shell.out"

	# execute the command and handle output if neccessary
        ret = system(arg)
        if not page_out:
            ch.send("Return value was %d" % ret)

        # cat the output to the character's page buffer
        else:
            try:
                fl = open("shell.out", "r")
                ch.page(fl.read())
                fl.close()
                unlink("shell.out")
            except:
                pass

# when the module is loaded, add the shell command to game
add_cmd("shell", None, cmd_shell, "unconcious", "flying",
        "admin", False, False)