# Copyright (C) 2011  Lukas Rist
# 
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
# 
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
# 
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.

import random

import functions


def output(s):
    print s


FUNCTIONS = functions.FUNCTIONS
WHITELIST = functions.WHITELIST

output("<?php\n//Generated by Glastopf sandbox.generate.py\n")
output("if(!extension_loaded('bfr')) {\n\tdl('bfr.so');\n}\n")
output("error_reporting(0);\n")

output("$functions = get_defined_functions();")
output("$functions = $functions['internal'];")

output("$whitelist = array(")
for i, function in enumerate(WHITELIST):
    output('\t\t%s => "%s",' % (i, function))
output(");")

output("$functions = array_diff($functions, $whitelist);\n")

output("foreach ($functions as $function){")
output("\t$rand_int = rand(100,999);")
output("\trename_function($function, $function.'_'.$rand_int);")
output("}\n")

int = 0
for function, return_val in FUNCTIONS.items():
    parts = function.split(";")
    function_name = parts[0]
    function_args = ", ".join(parts[1:-1])
    rand_int = random.randint(100, 999)
    output("override_function('%s', '%s', 'return %s_rep(%s);');" % (
    function_name, function_args, function_name, function_args))
    output("function %s_rep(%s) {" % (function_name, function_args))
    if return_val == "None":
        return_val = "\treturn;"
    output(return_val)
    #output("\terror_log(\"ret:%s(\" . join(', ', $args) . \")= \" . $result);" % function_name)
    output("}")
    output("rename_function('__overridden__', '%s');\n" % int)
    int += 1

output("\ninclude $argv[1];\n?>")
