<?php
    global $path;
    $status = 200;
    if (isset($_POST["data"]) && isset($_POST["key"])){
        $data = $_POST["data"];
        $key = $_POST["key"];
        if (json_decode($data) === null){
            error_log("ERROR: API v1 log-run: Invalid JSON");
            $status = 400;
        }
        else{
            $cmd = $_SERVER["DOCUMENT_ROOT"] . "/../application/bin/log-run.py " . $key . " " . escapeshellarg($data);
            $out = [];
            $ret = 0;
            exec($cmd, $out, $ret);
            if ($ret != 0){
                error_log("ERROR: API v1 log-run exited with status: " . $ret);
                error_log("====================");
                error_log("|| SCRIPT OUTPUT: ||");
                error_log("===============================================================================");
                foreach($out as $line){
                    error_log("|| " . $line);
                }
                error_log("===============================================================================");
                $status = 400;
            }
        }
    }
    else{
        error_log("ERROR: API v1 log-run: Invalid JSON");
        $status = 400;
    }
    http_response_code($status);
    return $status;
?>
