<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);

$remoteServer = "root@194.164.200.5";
$remoteScriptPath = "/root/letsencryptchron.sh";
$logFile = "/tmp/last_execution.log";
$scriptDir = dirname(__FILE__);
$uploadedKey = $scriptDir . "/uploaded_key";
$formSubmitted = false;

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['ppkFile'])) {
    if ($_FILES['ppkFile']['error'] === UPLOAD_ERR_OK) {
        if (move_uploaded_file($_FILES['ppkFile']['tmp_name'], $uploadedKey)) {
            echo "File uploaded!<br>";
            $formSubmitted = true;
        } else {
            echo "Failed to move the uploaded file.<br>";
            exit(1);
        }
    } else {
        echo "Upload error code: " . $_FILES['ppkFile']['error'] . "<br>";
        exit(1);
    }
}

if ($formSubmitted && file_exists($uploadedKey)) {
    chmod($uploadedKey, 0600);

    $sshCommand = "ssh -i $uploadedKey -o StrictHostKeyChecking=no $remoteServer 'bash $remoteScriptPath > $logFile 2>&1'";
    exec($sshCommand, $output, $returnVar);

    echo $returnVar === 0 ? "Remote script executed successfully.<br>" : "Remote script failed to execute.<br>";

    $logContents = shell_exec("ssh -i $uploadedKey -o StrictHostKeyChecking=no $remoteServer 'cat $logFile'");
    echo $logContents ? "<pre>" . htmlspecialchars($logContents) . "</pre>" : "No log output.<br>";

    // Cleanup
    if (file_exists($uploadedKey)) {
        unlink($uploadedKey);
        echo "File deleted!<br>";
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Upload Key and Run</title>
</head>
<body>
    <h2>Upload OpenSSH Private Key</h2>
    <?php if (!$formSubmitted): ?>
    <form action="VPSletsencryptcheck.php" method="post" enctype="multipart/form-data">
        <label for="ppkFile">Choose your private key:</label>
        <input type="file" name="ppkFile" id="ppkFile" required>
        <button type="submit">Upload & Run</button>
    </form>
    <?php endif; ?>
</body>
</html>
