<?php


echo "Toggle debug\n";

$debugDisabled = `grep "//debugLog" index.php -R | wc -l`;
if($debugDisabled > 0)
{
    $debugDisabled = true;
    echo "Debug disabled, enabling..\n";
}
else
{
    $debugDisabled = false;
    echo "Debug enabled, disabling..\n";
}


function scandir_through($dir)
{
    $blacklist = array(
        './toggleDebug.php' => false,
        './debug.php' => false,
        './testbackend.php' => false
    );
    $finalItems = array();
    $items = glob($dir . '/*');

    for ($i = 0; $i < count($items); $i++)
    {
        if (is_dir($items[$i]))
        {
            $dir = $items[$i];
            $finalItems = array_merge($finalItems, scandir_through($dir));
        }
        else if(is_file($items[$i]) && (strpos($items[$i], ".php") === false || strpos($items[$i], ".bak") !== false))
        {
            //echo $i . " rejected . " . $items[$i] . "\n";
        }
        else
        {
            print "checking " . $items[$i] . " in BLACKLIST\n";
            if(!array_key_exists($items[$i], $blacklist))
            {
                $finalItems[] = $items[$i];
            }
            else
            {
                print "in blacklist\n";
            }
        }
    }
    return $finalItems;
}


echo "Finding files...\n";

$files = scandir_through('.');

foreach($files as $file)
{
    echo "Processing " . $file . "\n";
    `cp $file $file.bak`;
    if($debugDisabled)
    {
        // enabled it
        `sed -e 's/\/\/debugLog(/debugLog(/g' $file.bak > $file`;
        if(strpos(`php -l $file`, 'No syntax errors') === false)
        {
            echo "$file FAILED syntax check.\n";
            `cp $file.bak $file`;
            unlink($file . ".bak");
        }
    }
    else
    {
        // disable it
       `sed -e 's/debugLog(/\/\/debugLog(/g' $file.bak > $file`;
        if(strpos(`php -l $file`, 'No syntax errors') === false)
        {
            echo "$file FAILED syntax check.\n";
            `cp $file.bak $file`;
            unlink($file . ".bak");
        }
    }
}

echo "Turning " . ($debugDisabled ? "On" : "Off") . " debug mode.\n";
`cp config.php config.php.bak`;
if($debugDisabled)
{
    // enabled it
    `sed -e "s/define('DEBUGGING', false)/define('DEBUGGING', true)/g" config.php.bak > config.php`;
    if(strpos(`php -l config.php`, 'No syntax errors') === false)
    {
        echo "config.php FAILED syntax check.\n";
        `cp config.php.bak config.php`;
        unlink("config.php.bak");
    }
}
else
{
    // disable it
    `sed -e "s/define('DEBUGGING', true)/define('DEBUGGING', false)/g" config.php.bak > config.php`;
    if(strpos(`php -l config.php`, 'No syntax errors') === false)
    {
        echo "config.php FAILED syntax check.\n";
        `cp config.php.bak config.php`;
        unlink("config.php.bak");
    }
}

echo "Completed\n";